How to Check If a Value Exists In a Multidimensional Array Using PHP?

Solution of how to check if a value exists in a multidimensional array in php.

Problem:

You might know how to find a value in an array or in a one dimensional array, but the same technique doesn’t work in a multidimensional array. So, you’re looking for the solution.

Solution:

Example:

<?php
function multi_array_search($search_for, $search_in) {
    foreach ($search_in as $element) {
        if ( ($element === $search_for) || (is_array($element) && multi_array_search($search_for, $element)) ){
            return true;
        }
    }
    return false;
}
$arr = array("2014", array("January", "February", "March"), "2015", array("Monday", "Tuesday"));
echo multi_array_search("Tuesday", $arr) ? 'Found' : 'Not found';
?>

Download Code272 downloads

Output:
Found

Explanation:

Line 10 Array $arr is a multidimensional array. It has arrays inside it.
Line 11 We’ll test if “Tuesday” exist in the array $arr. If it is found, the ternary operator will select “Found” otherwise Not Found” will be selected.The custom function multi_array_search() is called here. This function can find out a value in a multidimensional array.
Line 2 The multi_array_search() function starts here.
Line 3 The foreach loop goes through all the elements of the array $search_in. The elements could be a value or another array.
Line 4 to 5 If the array element is a value(not an array) and matches with the value we’re looking for(fulfilling this condition $element === $search_for), then it will return true in the next line(line 5).If an array element is another array(is_array($element)) which we test by the is_array() function, then we need to test all its elements (multi_array_search($search_for, $element)) to find out out desired value. And, if our target value is found inside this array, we’ll return true which we do in the next line(line 5). If you don’t understand yet how the two conditions are combined, then see the following simplified example.
Line 8 If the value is not found in any element of the multidimensional array, the function returns false.

Example: (simplified)

<?php
function multi_array_search($search_for, $search_in) {
    foreach ($search_in as $element) {
        if ( ($element === $search_for) ){
            return true;
        }elseif(is_array($element)){
            $result = multi_array_search($search_for, $element);
            if($result == true)
                return true;
        }
    }
    return false;
}
$arr = array("2014", array("January", "February", "March"), "2015", array("Monday", "Tuesday"));
echo multi_array_search("Tuesday", $arr) ? 'Found' : 'Not found';
?>
Download Code235 downloads


Pin It

↑ Back to Top