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.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…