2

I have an two associative arrayes and I want to check if

$array1["foo"]["bar"]["baz"] exists in $array2["foo"]["bar"]["baz"]

The values doesn't matter, just the "path". Does array_ intersect_ assoc do what I need?
If not how can I write one myself?

2
  • How do you know that you are looking for the path ["foo"]["bar"]["baz"]? Where do you get the information from? Commented Aug 1, 2009 at 22:38
  • I get the input from the URI. Commented Aug 2, 2009 at 3:48

2 Answers 2

6

Try this:

<?php
function array_path_exists(&$array, $path, $separator = '/')
{
    $a =& $array;
    $paths = explode($separator, $path);
    $i = 0;
    foreach ($paths as $p) {
        if (isset($a[$p])) {
            if ($i == count($paths) - 1) {
                return TRUE;
            }
            elseif(is_array($a[$p])) {
                $a =& $a[$p];
            }
            else {
                return FALSE;
            }
        }
        else {
            return FALSE;
        }
        $i++;
    }
}

// Test
$test = array(
    'foo' => array(
        'bar' => array(
            'baz' => 1
            )
        ),
    'bar' => 1
    );

echo array_path_exists($test, 'foo/bar/baz');

?>
Sign up to request clarification or add additional context in comments.

3 Comments

I will test it tomorrow. If it works can I credit you in my code?
A link to this question will do-- spread the word! (Assuming it does what you want...)
works with a minor change: I am using this preg_match_all('([\w.-]+)', $_SERVER['REQUEST_URI'], $paths); instead of explode as it doesn't fit the array I need. Thanks.
1

If you only need to check if the keys exist you could use a simple if statement.

<?php
if (isset($array1["foo"]["bar"]["baz"]) && isset($array2["foo"]["bar"]["baz"]

)) { //exists }

1 Comment

That works if I know the depth that I need to check. It's can also be array1["baz"]["bar"] exists in array2["baz"]["bar"] if there is a different input.

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.