Array_filter and multidimensional array
Let's say I have an array, for example:
$arr[] = array("id" => 11, "name" => "First"); $arr[] = array("id" => 52, "name" => "Second"); $arr[] = array("id" => 6, "name" => "Third"); $arr[] = array("id" => 43, "name" => "Fourth");
I would like to get a name corresponding to a specific identifier so that I can:
$name = findNameFromID(43);
and get, for example, "Fourth."
I was thinking about using array_filter
, but I'm a little fixated on how to pass the variable correctly. I saw questions like this one , but it seems like I cannot extend the solution for a multidimensional array.
Any help?
findNameFromID($array,$ID) { return array_values(array_filter($array, function($arrayValue) use($ID) { return $arrayValue['id'] == $ID; } )); } $name = findNameFromID($arr,43); if (count($name) > 0) { $name = $name[0]['name']; } else { echo 'No match found'; }
PHP 5.3.0 and later
EDIT
or option:
findNameFromID($array,$ID) { $results = array_values(array_filter($array, function($arrayValue) use($ID) { return $arrayValue['id'] == $ID; } )); if (count($results) > 0) { return $name[0]['name']; } else { return FALSE; } } $name = findNameFromID($arr,43); if (!$name) { echo 'No match found'; }
EDIT No. 2
And from PHP 5.5 we can use array_column ()
findNameFromID($array, $ID) { $results = array_column($array, 'name', 'id'); return (isset($results[$ID])) ? $results[$ID] : FALSE; }