Skip to content
PHP Logo

What are the common pitfalls when searching for a specific value within a nested array in PHP?

One common pitfall when searching for a specific value within a nested array in PHP is not properly iterating through all levels of the nested array. To avoid this issue, you can use a recursive function to search through each level of the array until the value is found or all elements have been checked.

php
function searchNestedArray($array, $value) {
    foreach ($array as $element) {
        if (is_array($element)) {
            $result = searchNestedArray($element, $value);
            if ($result !== false) {
                return $result;
            }
        } else {
            if ($element === $value) {
                return true;
            }
        }
    }
    
    return false;
}

// Example of searching for a value in a nested array
$array = [
    'a',
    'b',
    ['c', 'd', ['e', 'f']],
    'g',
];

if (searchNestedArray($array, 'e')) {
    echo 'Value found in nested array!';
} else {
    echo 'Value not found in nested array.';
}