How to check if element is in a nested array php??

by hal.littel , in category: PHP General , 6 months ago

How to check if element is in a nested array php??

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 6 months ago

@hal.littel 

To check if an element is present in a nested array in PHP, you can use a recursive function. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function checkElementInNestedArray($element, $array) {
    foreach ($array as $value) {
        if (is_array($value)) {
            if (checkElementInNestedArray($element, $value)) {
                return true;
            }
        } else {
            if ($value == $element) {
                return true;
            }
        }
    }
    
    return false;
}

// Usage example:
$array = [1, 2, [3, 4, [5, 6]], 7];
$element = 5;

if (checkElementInNestedArray($element, $array)) {
    echo "Element is present in the nested array.";
} else {
    echo "Element is not present in the nested array.";
}


In this example, the checkElementInNestedArray function checks if an element $element is present in the nested array $array. It loops through each element of $array and checks if the value is an array or not. If it is an array, the function is called recursively on that array. If the value is not an array, it checks if it matches the element being searched for. The function returns true if the element is found, and false otherwise.


You can modify the example based on your specific requirements.