The key is already the ... ehm ... key

echo $array[20120504];

If you are unsure, if the key exists, test for it

$key = 20120504;
$result = isset($array[array[$key] : null;

Minor addition:

$result = @$array[$key] ?: null;

One may argue, that @ is bad, but keep it serious: This is more readable and straight forward, isn't?

Update: With PHP7 my previous example is possible without the error-silencer

$result = $array[$key] ?? null;
Answer from KingCrunch on Stack Overflow
๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ function.array-search.php
PHP: array_search - Manual
array_search โ€” Searches the array for a given value and returns the first corresponding key if successful
๐ŸŒ
W3Schools
w3schools.com โ€บ php โ€บ func_array_search.asp
PHP array_search() Function
MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data ยท PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser ยท AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll ยท PHP Examples PHP Compiler PHP Quiz PHP Exercises PHP Server PHP Syllabus PHP Study Plan PHP Certificate ... array() array_change_key_case() array_chunk() array_column() array_combine() array_co
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ how-to-search-by-multiple-key-value-in-php-array
How to search by multiple key => value in PHP array ? - GeeksforGeeks
July 15, 2024 - To search for elements in a PHP array based on multiple key-value pairs without using foreach, utilize array_filter() with a callback that checks matches using array_intersect_assoc().
๐ŸŒ
Inspector
inspector.dev โ€บ home โ€บ how to search in a php associative array โ€“ fast tips
How to Search in a PHP Associative Array - inspector.dev
July 1, 2025 - $targetValue = 'yellow'; foreach ($colors as $key => $value) { if ($value === $targetValue) { echo "The value {$targetValue} is associated with the key {$key}."; break; // Optional: Stop searching after finding the occurrence.
๐ŸŒ
Reddit
reddit.com โ€บ r/php โ€บ given a key, what's the most elegant way to get the previous and next elements in an array?
r/PHP on Reddit: Given a key, what's the most elegant way to get the previous and next elements in an array?
May 28, 2017 - Share and discover the latest news about the PHP ecosystem and its community. Please respect r/php's rules. ... Fetch all keys with array_keys() then array_search() for the key, and -- and ++ in the keys list, to get prev/next.
๐ŸŒ
3D Bay
clouddevs.com โ€บ home โ€บ php guides โ€บ working with phpโ€™s array_search() function: a practical guide
Working with PHP's array_search() Function: A Practical Guide
December 11, 2023 - At its core, this function searches for a value within an array and returns the corresponding key if the value is found. If the value is not found, it returns false. ... $strict (optional): A boolean parameter that specifies whether the search ...
Find elsewhere
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ php โ€บ php_function_array_search.htm
PHP - Function array_search()
The array_search() function search an array for a value and returns the key. It returns the key if it is found in the array, FALSE otherwise. ... <?php $input = array("a"=>"banana","b"=>"apple","c"=>"Mango"); print_r(array_search("apple", $input)); ?>
๐ŸŒ
GitHub
gist.github.com โ€บ 3671626
PHP Array key search for matching string. ยท GitHub
PHP Array key search for matching string. GitHub Gist: instantly share code, notes, and snippets.
Top answer
1 of 2
1

Firstly, this could use a better description (in a comment) explaining what it does. I had to figure it out from the code. I think the description should probably be something like

// Searches $array for associative arrays which are supersets of $parameters.
// If $multipleResults it will return all matches in an array;
// otherwise just the first, in an array.

Secondly, names.

  • findValue isn't very descriptive. How about findSupersets?
  • $array would traditionally be called $haystack in PHP, since you're searching through it for matches to a predicate.
  • $multipleResoult is a misspelling. Correcting the spelling and adjective-noun agreement we get $multipleResults, which is ok, although I personally would prefer to communicate an action: $returnAll.
  • $suspicious has the wrong connotations for this native English speaker. If something is suspicious, it means that I think there's something wrong with it. My preferred variable name for something which may or may not pass an acceptance test is $candidate.

Thirdly, since PHP has a dynamic type system I think it would be more idiomatic to return just the element if !$multipleResults, rather than wrapping it in an array.


Now, you specifically ask whether there's a simpler way to do it. I think that using booleans it can be simplified quite a bit by inverting the assumption. Rather than prove it acceptable, prove it not acceptable. Taking into account various of my suggestions above and refactoring I get:

    foreach($haystack as $childArray){
        $isCandidate = true;
        foreach($parameters as $k => $p){
            if(!array_key_exists($k,$childArray) || $childArray[$k] != $p){
                $isCandidate = false;
                break;
            }
        }
        if($isCandidate){
            if(!$multipleResults){
                return $childArray;
            }
            $result[] = $childArray;
        }
    }

    return $result;

It's a couple of years now since I used PHP, and I'm not sure offhand whether there are built-in functions to test whether $childArray contains $parameters as a subset, or to filter an array by a predicate. It may be that the whole function can be reduced to two calls to built-ins. If not, you could consider whether you want to factor it out as

function findMatch(array $haystack, $predicate, $returnAll = false) {
    $results = []
    foreach ($haystack as $element) {
        if ($predicate($element)) {
            if ($returnAll) return $element;
            $results[] = $element;
        }
    }
    return $results;
}

function isSuperset(array $candidate, array $subset) {
    foreach ($subset as $k => $v) {
        if (!isset($candidate[$k]) || $candidate[$k] != $v) return false;
    }
    return true;
}

linking the two with a lambda.

2 of 2
1

You don't need to call a second foreach loop and temporarily store partial matches (suspicious/candidates) as you go.
Use array_intersect_assoc() and sizeof() (or count()) to instantly identify qualifying subarrays.

Code: (Demo)

function findValue(array $array, array $terms, $get_all=false){
    $term_count=sizeof($terms);  // cache the element count of $terms
    $results=[]; // establish empty array for print_r if no matches are found.
    foreach($array as $subarray){
        if(sizeof(array_intersect_assoc($subarray,$terms))==$term_count){ // qualifying subarray
            if(!$get_all){
                return $subarray;  // end loop and return the single subarray
            }else{
                $results[]=$subarray;
            }
        }
    }
    return $results;
}
Top answer
1 of 16
238

Code:

function search($array, $key, $value)
{
    $results = array();

    if (is_array($array)) {
        if (isset($array[$key]) && $array[$key] == $value) {
            $results[] = $array;
        }

        foreach ($array as $subarray) {
            $results = array_merge($results, search($subarray, $key, $value));
        }
    }

    return $results;
}

$arr = array(0 => array(id=>1,name=>"cat 1"),
             1 => array(id=>2,name=>"cat 2"),
             2 => array(id=>3,name=>"cat 1"));

print_r(search($arr, 'name', 'cat 1'));

Output:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => cat 1
        )

    [1] => Array
        (
            [id] => 3
            [name] => cat 1
        )

)

If efficiency is important you could write it so all the recursive calls store their results in the same temporary $results array rather than merging arrays together, like so:

function search($array, $key, $value)
{
    $results = array();
    search_r($array, $key, $value, $results);
    return $results;
}

function search_r($array, $key, $value, &$results)
{
    if (!is_array($array)) {
        return;
    }

    if (isset($array[$key]) && $array[$key] == $value) {
        $results[] = $array;
    }

    foreach ($array as $subarray) {
        search_r($subarray, $key, $value, $results);
    }
}

The key there is that search_r takes its fourth parameter by reference rather than by value; the ampersand & is crucial.

FYI: If you have an older version of PHP then you have to specify the pass-by-reference part in the call to search_r rather than in its declaration. That is, the last line becomes search_r($subarray, $key, $value, &$results).

2 of 16
78

How about the SPL version instead? It'll save you some typing:

// I changed your input example to make it harder and
// to show it works at lower depths:

$arr = array(0 => array('id'=>1,'name'=>"cat 1"),
             1 => array(array('id'=>3,'name'=>"cat 1")),
             2 => array('id'=>2,'name'=>"cat 2")
);

//here's the code:

    $arrIt = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));

 foreach ($arrIt as $sub) {
    $subArray = $arrIt->getSubIterator();
    if ($subArray['name'] === 'cat 1') {
        $outputArray[] = iterator_to_array($subArray);
    }
}

What's great is that basically the same code will iterate through a directory for you, by using a RecursiveDirectoryIterator instead of a RecursiveArrayIterator. SPL is the roxor.

The only bummer about SPL is that it's badly documented on the web. But several PHP books go into some useful detail, particularly Pro PHP; and you can probably google for more info, too.

๐ŸŒ
Reintech
reintech.io โ€บ blog โ€บ mastering-php-array-search-function-array-searching-filtering
Mastering PHP's `array_search()` Function for Array Searching and Filtering | Reintech media
April 14, 2023 - In PHP, the `array_search()` function is used to search for a specific value in an array and return the corresponding key if the value is found. It can perform either strict or loose comparison, depending on the optional third parameter.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-search-by-key-value-in-a-multidimensional-array-in-php
How to Search by key=value in a Multidimensional Array in PHP
Here's an example of using array_filter() and array_column() to search for a key-value pair in a multidimensional array in PHP:
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ how-to-search-by-keyvalue-in-a-multidimensional-array-in-php
How to search by key=>value in a multidimensional array in PHP ? - GeeksforGeeks
July 15, 2024 - ... <?php // PHP program to carry out multidimensional array // search by key=>value // Function to recursively search for a // given key=>value function search($array, $key, $value) { $results = array(); // if it is array if (is_array($array)) ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ php-array_search-function
PHP array_search() Function - GeeksforGeeks
September 12, 2024 - The PHP array_search() function searches an array for a specific value and returns the first corresponding key if found.