2

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.

2 Answers 2

4

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 ) );
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.