Monday 13 August 2018

How to Check If a Value Exists In a Multidimensional Array Using 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:
1
2
3
4
5
6
7
8
9
10
11
12
<?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';
?>

Output:Found
Explanation:
Line 10Array $arr is a multidimensional array. It has arrays inside it.
Line 11We’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 functionmulti_array_search() is called here. This function can find out a value in a multidimensional array.
Line 2The multi_array_search() function starts here.
Line 3The foreach loop goes through all the elements of the array $search_in. The elements could be a value or another array.
Line 4 to 5If 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 8If the value is not found in any element of the multidimensional array, the function returns false.
Example: (simplified)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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';
?>

0 comments:

Post a Comment