nico
nico

Reputation: 51670

Search a 2d array by one column value and return another value from the qualifying row

Say I have an array such as:

$arr[] = array("id" => 11, "name" => "First");
$arr[] = array("id" => 52, "name" => "Second");
$arr[] = array("id" => 6, "name" => "Third");
$arr[] = array("id" => 43, "name" => "Fourth");

I would like to get the name correspondent to a certain ID so that I can do:

$name = findNameFromID(43);

and get, for instance, "Fourth".

I thought of using array_filter but I am a bit stuck on how to correctly pass a variable. I have seen questions such as this one but I don't seem to be able to extend the solution to a multidimensional array.

Any help?

Upvotes: 10

Views: 15146

Answers (2)

mickmackusa
mickmackusa

Reputation: 48001

From PHP8.4, use array_find() as the functional style equivalent of a short circuiting loop. This provides elegance without requiring the full array to be traversed unconditionally. Demo

$find = 43;
var_export(
    array_find($arr, fn($row) => $row['name'] === $find)[$find] ?? null
);

Old answer:

I don't think I'd bother to declare a custom function for such a basic task. Restructure the 2d array into an associative map, then attempt to access the map data with the search value as the key. Fallback to null if the element is not found.

Code: (Demo)

$find = 43;
var_export(
    array_column($arr, 'name', 'id')[$find] ?? null
);

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212472

findNameFromID($array,$ID) {
     return array_values(array_filter($array, function($arrayValue) use($ID) { return $arrayValue['id'] == $ID; } ));
}

$name = findNameFromID($arr,43);
if (count($name) > 0) {
    $name = $name[0]['name'];
} else {
    echo 'No match found';
}

PHP 5.3.0 and above

EDIT

or variant:

findNameFromID($array,$ID) {
    $results = array_values(array_filter($array, function($arrayValue) use($ID) { return $arrayValue['id'] == $ID; } ));
    if (count($results) > 0) {
        return $name[0]['name'];
    } else {
        return FALSE;
    }
}

$name = findNameFromID($arr,43);
if (!$name) {
    echo 'No match found';
}

EDIT #2

And from PHP 5.5, we can use array_column()

findNameFromID($array, $ID) {
    $results = array_column($array, 'name', 'id');
    return (isset($results[$ID])) ? $results[$ID] : FALSE;
}

Upvotes: 14

Related Questions