How to check if an element exist in array of array in php?

Member

by jasen , in category: PHP General , 10 months ago

How to check if an element exist in array of array in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , 10 months ago

@jasen 

To check if an element exists in an array of arrays in PHP, you can use a nested foreach loop and check each element individually. Here is 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 searchElement($array, $element) {
    foreach($array as $subarray) {
        foreach($subarray as $value) {
            if($value == $element) {
                return true;
            }
        }
    }
    return false;
}

// Example usage
$myArray = array(
    array(1, 2, 3),
    array(4, 5, 6),
    array(7, 8, 9)
);

$element = 5;

if(searchElement($myArray, $element)) {
    echo "Element exists in the array.";
} else {
    echo "Element does not exist in the array.";
}


In this example, the function searchElement takes in the array and the element you want to search for. It then iterates over each subarray and each value in the subarray, checking if it matches the element you are searching for. If a match is found, it returns true. If no match is found, it returns false.


You can replace the $myArray and $element variables with your own array and element to search for in order to check if an element exists in your specific array of arrays.