I’m building a web API which takes an array of data. I want to check this array for certain keys and if a required key doesn’t exist, return false and if an optional key doesn’t exist, set that key-value pair in the array.
The confusion comes from my input array having potentially arrays as values. For example, let’s say I input an array like this:
$input_array = array(
’name’ => ‘Adam’,
‘address’ => array(
‘number’ => 12,
‘street’ => ‘My Street’
)
);
I have required keys:
$required_keys = array(
‘name’,
‘address’ => array(
‘number’,
‘street’
)
);
Optional keys:
$optional_keys = array(
‘address’ = array(
‘postcode’ => ‘WA1'
)
);
I’m struggling of a way to test my input array against these two types of test arrays (input and optional).
What should happen is: 1) All of the required keys should be matched. 2) If any optional keys don’t exist, set them to the key-value pair from the optional keys array.
I know of (but am not experienced with) regular expressions. However, I do know that PHP has a function called http_build_query(mixed $array); which takes an array and turns it in to a URL query string. My thoughts are maybe I could turn the input array into a URL string then compare it against a regular expression made of my two test arrays (required and optional). Would/could this work?
If anyone has any other ideas I’d love to know. Thanks
Update: Attached unsuspected output

Update 2: Attached new output

Update 3: Current code:
static public function static_test_required_keys(Array $required_keys_array, Array $input_array)
{
$missing = array();
foreach ($required_keys_array as $key => $value)
{
if (empty($input_array[$key]))
{
$missing[] = $key;
}
else if (isset($input_array[$key]) && is_array($input_array[$key]))
{
$missing = array_merge(Inputter::static_test_required_keys($value, $input_array[$key]), $missing);
}
}
return $missing;
}
Update 4: New code.
tatic public function static_test_required_keys(Array $required_keys_array, Array $input_array)
{
$missing = array();
foreach ($required_keys_array as $key => $value)
{
if (! isset($input_array[$key]))
{
$missing[] = $key;
}
else if (isset($input_array[$key]) && is_array($input_array[$key]))
{
$missing = array_merge(Inputter::static_test_required_keys($value, $input_array[$key]), $missing);
}
}
return $missing;
}
Changed the code from isempty() to isset(). This page gives the differences between the two. https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/