Skip to content

Instantly share code, notes, and snippets.

@lomholdt
Last active November 20, 2018 13:38
Show Gist options
  • Select an option

  • Save lomholdt/98e42c718c50938c6c0ea85dd6d98e3f to your computer and use it in GitHub Desktop.

Select an option

Save lomholdt/98e42c718c50938c6c0ea85dd6d98e3f to your computer and use it in GitHub Desktop.
A recursive implementation of array_key_exists
<?php
function array_key_exists_recursive($key, $arr)
{
if (array_key_exists($key, $arr)) {
return true;
}
foreach ($arr as $currentKey => $value) {
if (is_array($value)) {
return array_key_exists_recursive($key, $value);
}
}
return false;
}
@giro83
Copy link

giro83 commented Nov 20, 2018

Your function has a bug.

Inside the foreach, you cannot return unless you're returning true. Otherwise, you will not finish traversing all possible sub-arrays.

Demo:

<?php

$test = array(
   'key1' => array(
      'key2' => 'foo',
   ),
   'key3' => array(
      'key4' => 'bar',
      'key5' => 'hello',
      'key6' => 'bye',
   ),
);

function array_key_exists_recursive($key, $arr)
{
    if (array_key_exists($key, $arr)) {
        return true;
    }
    foreach ($arr as $currentKey => $value) {
        if (is_array($value)) {
            return array_key_exists_recursive($key, $value);
        }
    }
    return false;
}


function my_array_key_exists_recursive($key, $arr) {
   if (array_key_exists($key, $arr)) {
      return true;
   }
   foreach ($arr as $curval) {
      if (is_array($curval)) {
         if (my_array_key_exists_recursive($key, $curval)) {
            return true;
         }
      }
   }
   return false;
}

if (array_key_exists_recursive('key5', $test)) {
   echo "yep ";
}
else {
   echo "nope ";
}

if (my_array_key_exists_recursive('key5', $test)) {
   echo "yep ";
}
else {
   echo "nope ";
}

?>

A similar function is discussed here: https://murviel-info-beziers.com/fonction-recursive-array_key_exists-php/ (in French).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment