A different method to finding values in an associated or nested array rather than use a loop.
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() 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"
)
);
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Some early September spring shots from a bushwalk, It is still too early for wildflowers.
I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…
If you ever needed a simple solution in Laravel to delete an entire directory and…
How to enforce only one user to register or be registered in a Laravel web…