chap
chap

Reputation: 1869

How to build the keys of a multidimensional array in PHP from the values of another array?

I have a problem that I'm struggling to solve.

I have two arrays.

One is

$array1 = array('eligibility', 'eligibility_section');

But it could be an unknown length.

The other will hopefully contain the values above in its keys. Eg it might look like this.

$array2 = array('eligibility' => array('eligibility_section' => 'some_val));

I need a way to check if the values in array1 exist as keys in array2, and they must exist in the same order. E.g. from the example above if the order of array1 was:

array('eligibility_section', 'eligibility'); 

The method would return false.

Sorry if its a stupid question but I'm very tired.

Upvotes: 2

Views: 67

Answers (2)

Avag Sargsyan
Avag Sargsyan

Reputation: 2523

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 ) );

Upvotes: 4

deceze
deceze

Reputation: 522597

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 be null for this to return the correct result:

array_reduce($array1, function ($s, $k) { return $s[$k] ?? false; }, $array2)

Upvotes: 1

Related Questions