views:

133

answers:

3

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?

A: 

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 }

Glass Robot
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.
the_drow
A: 

array_key_exists?

meder
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.
the_drow
+1  A: 

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

?>
Ken Keenan
I will test it tomorrow.If it works can I credit you in my code?
the_drow
A link to this question will do-- spread the word! (Assuming it does what you want...)
Ken Keenan
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.
the_drow