Tags
Asked 3 years ago
9 Jun 2021
Views 387
steave

steave posted

in_array() and multidimensional array in php ?

how to use in_array() at multidimensional array in php ?
sandip

sandip
answered Apr 26 '23 00:00

The in_array () function in PHP is used to check if a given value exists in an array. However, it only works for one-dimensional arrays. If you want to check for the existence of a value in a multidimensional array, you can use a loop to iterate through each level of the array and check each element individually.

Here's an example of how you can check if a value exists in a multidimensional array using a loop:


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

In this example, the in_multidimensional_array () function takes two arguments: the value to search for and the array to search in. It uses a foreach loop to iterate through each element of the array. If the current element is itself an array, the function is called recursively to check each element of the sub-array. If the current element is not an array, it is compared to the search value using the == operator.

If the search value is found in the array, the function returns true . If the entire array has been searched and the value has not been found, the function returns false .

You can use this function to check for the existence of a value in a multidimensional array like this:


$my_array = array(
    array("apple", "banana", "cherry"),
    array("orange", "pear", "plum")
);

if (in_multidimensional_array("banana", $my_array)) {
    echo "The value 'banana' was found in the array!";
} else {
    echo "The value 'banana' was not found in the array.";
}

In this example, the in_multidimensional_array () function is called with the value "banana" and the $ my_array array. Since "banana" is a value in the array, the function will return true, and the message "The value 'banana' was found in the array!" will be displayed.
Post Answer