How to build the keys of a multidimensional array in PHP from the values of another array?
Get the solution ↓↓↓Solution:
Hopefully the following code will solve your problem.
$array1 = array('eligibility', 'eligibility_section', 'some_key');
$array2 = array('eligibility' => array('eligibility_section' => array('some_key' => 'some_val' ) ) );
function is_keys_exist( $array1, $array_to_compare ) {
$i = 0;
foreach( $array_to_compare as $key1 => $val1 ) {
if( $key1 !== $array1[$i] ) {
return false;
}
++$i;
if( is_array( $val1 ) ) {
is_keys_exist( $array1, $val1 );
}
}
return true;
}
var_dump( is_keys_exist( $array1, $array2 ) );
Answer
Solution:
This can be done with a simple array reduction:
$array1 = array('eligibility', 'eligibility_section');
$array2 = array('eligibility' => array('eligibility_section' => 'some_val'));
$result = array_reduce($array1, function ($subject, $key) {
return is_array($subject) && array_key_exists($key, $subject) ? $subject[$key] : false;
}, $array2);
echo $result ? 'true' : 'false';
With the PHP 7 null coalescing operator this can be shortened to this, though beware that your values must not benull
for this to return the correct result:
array_reduce($array1, function ($s, $k) { return $s[$k] ?? false; }, $array2)
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the browser (or proxy) sent a request that this server could not understand.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.