A different method to finding values in an associated or nested array rather than use a loop.
Looping
The seemingly easiest way is to do a loop and when the key equals a value output what we want:
foreach ($haystack as $h) { if ($h['id'] === 6) { echo $h['name'];//Apple } }
This is alright for small arrays but once you get into the several hundreds or thousands is looping through every iteration optimal?
array_column
array_column() gets used. It returns the values from a single column as identified by the column key. You can also add in an index key which then returns the values from the index key column.
Essentially this code below is checking if a match was found
$filter = array_column($haystack, 'name', 'id'); $id = '6'; if (isset($filter[$id])) { echo $filter[$id];//Apple }
The isset conditional is only met when the index is what was being searched.
The example array:
$haystack = array( array( "id" => 1, "name" => "Lemon" ), array( "id" => 2, "name" => "Lime" ), array( "id" => 3, "name" => "Mango" ), array( "id" => 4, "name" => "Orange" ), array( "id" => 5, "name" => "Peach" ), array( "id" => 6, "name" => "Apple" ), array( "id" => 7, "name" => "Pear" ), array( "id" => 8, "name" => "Melon" ), array( "id" => 9, "name" => "Banana" ), array( "id" => 10, "name" => "Kiwi" ) );