Find the array and return all keys and values ​​if a match is found

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

 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 John Doe search, he would be back.

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

It would be easier to rename arrays based on what I'm looking for. Instead of the specified array, I can also create 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 ) ) 
+8
arrays php
source share
3 answers
 $filteredArray = array_filter($array, function($element) use($searchFor){ return isset($element['name']) && $element['name'] == $searchFor; }); 

PHP 5.3.x required

+6
source share
 function search_array( $array, $name ){ foreach( $array as $item ){ if ( is_array( $item ) && isset( $item['name'] )){ if ( $item['name'] == $name ){ // or other string comparison return $item; } } } return FALSE; // or whatever else you'd like } 
+1
source share

I would suggest an optional change to the scibuff response (which was great). If you are not looking for an exact match, but a string inside an array ...

 function array_search_x( $array, $name ){ foreach( $array as $item ){ if ( is_array( $item ) && isset( $item['name'] )){ if (strpos($item['name'], $name) !== false) { // changed this line return $item; } } } return FALSE; // or whatever else you'd like } 

Call it ...

 $pc_ct = array_search_x($your_array_name, 'your_string_here'); 
+1
source share

All Articles