Home >Backend Development >PHP Tutorial >How Can I Efficiently Search Multidimensional Arrays in PHP?

How Can I Efficiently Search Multidimensional Arrays in PHP?

DDD
DDDOriginal
2024-12-26 20:11:10675browse

How Can I Efficiently Search Multidimensional Arrays in PHP?

Searching Multidimensional Arrays with in_array()

While the in_array() function is a convenient tool for checking the existence of a value within an array, it falls short when dealing with arrays that possess a multidimensional structure. To overcome this limitation, consider the following:

Custom Recursive Function

Instead of relying on in_array(), you can employ a recursive function like in_array_r:

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

Usage:

To utilize the in_array_r function, provide it with the needle (value you seek), the haystack (multidimensional array), and an optional strict parameter (controls strict equality comparison). For example:

$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';

The above is the detailed content of How Can I Efficiently Search Multidimensional Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn