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
)
)
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.
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.
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.
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.
$filteredArray =
array_filter($array, function($element) use($searchFor){
return isset($element['name']) && $element['name'] == $searchFor;
});
Requires PHP 5.3.x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With