Categories: Development

A different approach to searching an associative array with PHP

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"
    )
);

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago