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

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

3 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

3 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

3 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

3 years ago