'How to check if element is in a Nested Array PHP?

USE CASE :

$a = [1, 2, [3, 4, 5], [6, [7, 8], 8, 10]];
isNumberPresentInArray($a, 10) // returns true;
isNumberPresentInArray($a, 2) // returns true;
isNumberPresentInArray($a, 14) // returns false;

I would like to check if there element exist in array.The following is my version of code. but its not working perfectly for inner arrays. Please help me.

$a = [1, 2, [3, 4, 5], [6, [7, 8], 8, 10]];

function isNumberPresentInArray($a, $b) {
    foreach($a as $v)
    {
        if (is_array($v)) {
            return isNumberPresentInArray($v, $b);
        } else {
            if ($v == $b) {
                return true;
            }
        }
    }
}

echo isNumberPresentInArray($a, 1);


Solution 1:[1]

You could use an iterator:

$arr = [ 1, 2, [ 3, 4, 5 ], [ 6, [ 7, 8 ], 9, 10 ] ];

function isNumberPresentInArray(array $arr, int $number): bool {
  $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr), RecursiveIteratorIterator::LEAVES_ONLY);
  foreach ($it as $value) {
    if ($value === $number) {
      return true;
    }
  }
  return false;
}

echo '10: ' . ( isNumberPresentInArray($arr, 10) ? 'yes' : 'no' ) . "\n";
echo ' 2: ' . ( isNumberPresentInArray($arr, 2) ? 'yes' : 'no' ) . "\n";
echo '14: ' . ( isNumberPresentInArray($arr, 14) ? 'yes' : 'no' ) . "\n";

This will print:

10: yes
 2: yes
14: no

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1