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.
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
}
I would like to offer an optional change to scibuff's answer(which was excellent). If you are not looking for an exact match, but a string inside the 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 this with...
$pc_ct = array_search_x($your_array_name, 'your_string_here');
$filteredArray =
array_filter($array, function($element) use($searchFor){
return isset($element['name']) && $element['name'] == $searchFor;
});
Requires PHP 5.3.x