Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search array and return all keys and values when match found

Tags:

arrays

php

I like to perform a search on an array and return all values when a match is found. The key [name] in the array is what I am doing a search on.

Array (
[0] => Array
    (
        [id] => 20120100
        [link] => www.janedoe.com
        [name] => Jane Doe
    )
[1] => Array
    (
        [id] => 20120101
        [link] => www.johndoe.com
        [name] => John Doe
    )
)

If I did a search for John Doe it would return.

Array
(
    [id] => 20120101
    [link] => www.johndoe.com
    [name] => John Doe
)

Would it be easier to rename the arrays based on what I am searching for. Instead of the above array I can also generate the following.

Array (
[Jane Doe] => Array
    (
        [id] => 20120100
        [link] => www.janedoe.com
        [name] => Jane Doe
    )
[John Doe] => Array
    (
        [id] => 20120101
        [link] => www.johndoe.com
        [name] => John Doe
    )
)
like image 968
Tim Avatar asked Feb 25 '12 00:02

Tim


People also ask

How do you match a key in an array?

The array_intersect_key() function compares the keys of two (or more) arrays, and returns the matches. This function compares the keys of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

Which function searches an array for a specific value?

The array_search() is an inbuilt function in PHP that is used to search for a particular value in an array, and if the value is found then it returns its corresponding key. If there are more than one values then the key of the first matching value will be returned.

How do you find array keys?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

How do you check if an array contains a key?

The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.


1 Answers

$filteredArray = 
array_filter($array, function($element) use($searchFor){
  return isset($element['name']) && $element['name'] == $searchFor;
});

Requires PHP 5.3.x

like image 132
iBiryukov Avatar answered Oct 21 '22 07:10

iBiryukov