Let’s say I have two arrays, one is of keys I require, the other is an array I want to test against.
In the array of keys I require, each key might have a value which is itself an array of keys I require, and so on.
Here’s the function so far:
static function keys_exist_in_array(Array $required_keys, Array $values_array, &$error)
{
foreach($required_keys as $key)
{
// Check required key is set in the values array
//
if (! isset($values_array[$key]))
{
// Required key is not set in the values array, set error and return
//
$error = new Error();
return false;
}
// Check the value is an array and perform function on its elements
//
if (is_array($values_array[$key]))
{
Static::keys_exist_in_array($required_keys[$key], $values_array[$key], $error);
}
return true;
}
}
My problem is that the array I want to submit to $required_keys
CAN look like this:
$required_keys = array(
‘key1’,
‘key2’,
‘key3’,
‘key4’ = array(
‘key1’,
‘key2’,
‘key3’ = array(
‘key1’
)
)
);
Obviously the problem here is that foreach
only finds each key, e.g. ‘key4’, rather than the values without their own value, e.g. ‘key1’, ‘key2’, ‘key3’.
But if I loop through with a standard for loop, I only get the values, key1, key2, key3.
What’s a better way of doing this?
Thanks