0

I got the follwing array and I would like to retrieve the name by the id:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => john
        )
    [1] => Array
        (
            [id] => 2
            [name] => mark
        )
etc...

It is doable with double foreach loop and a conditional test, but is there a more elegant way?

1
  • A foreach is probably the quickest way of doing this as most other ways involve at least 1 pass of the entire array to convert it to a id => name array (unless you can generate this in the first place). Commented Feb 1, 2020 at 20:13

2 Answers 2

2

Assuming that id is unique...

Long Version

$arr = [
    ['id'=1, 'name'='john'],
    ['id'=2, 'name'='mark'],
];

$lookup = [];
foreach($arr as $row) {
    $id = $row['id'];
    $name = $row['name'];
    $lookup[$id] = $name;
}

// find name for id, 2
echo $lookup[2];

// ==> mark

Short Version

...see Progrock’s solution!

Sign up to request clarification or add additional context in comments.

Comments

1

You can use array_column to map ids to names:

<?php

$arr = [
    ['id' => 1, 'name' => 'Rolf'],
    ['id' => 3, 'name' => 'Gary'],
    ['id' => 2, 'name' => 'Jimmy'],
];


$id_names = array_column($arr, 'name', 'id');

var_export($id_names);

print $id_names[3];

Output:

array (
  1 => 'Rolf',
  3 => 'Gary',
  2 => 'Jimmy',
)Gary

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.