Chris
Chris

Reputation: 59541

PHP - Get key value from other key

I have the following array:

$array = Array(
    "0" => Array (
        "id" => 1081,
        "name" => "John"
    ), 
    "1" => Array (
        "id" => 1082,
        "name" => "Matt"
    ),
    "2" => Array (
        "id" => 1083,
        "name" => "Roger"
    )
);

Is there anyway I can get name if I only know the id but without having to iterate through the array?

Upvotes: 0

Views: 67

Answers (3)

Adrian Cid Almaguer
Adrian Cid Almaguer

Reputation: 7791

You can use array_map to search into your array if your PHP < 5.5.0 and you don't have array_column:

<?php

$array = Array(
    "0" => Array (
        "id" => 1081,
        "name" => "John"
    ), 
    "1" => Array (
        "id" => 1082,
        "name" => "Matt"
    ),
    "2" => Array (
        "id" => 1083,
        "name" => "Roger"
    )
);

$find = 1082;
$value = '';

$arr = array_map(function($n) use ($find, &$value) {if ($n['id'] == $find) $value = $n['name']; }, $array);


print_r($value);

?>

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 79024

For PHP >= 5.5.0:

$id = 1082;
$result = array_column($array, 'name', 'id')[$id];

As Barmar points out, to get an array that is easy to use with id as the index:

$id = 1082;
$result = array_column($array, 'name', 'id');
echo $result[$id];

Upvotes: 2

Barmar
Barmar

Reputation: 782693

You can make an associative array that refers to the same elements, then use that:

function make_assoc(&$array, $keyname) {
    $new_array = array();
    foreach ($array as &$elt) {
        $new_array[$elt[$keyname]] = $elt;
    }
    return $new_array;
}

$assoc_array = make_assoc($array, 'id');

Now you can use $assoc_array[1083] to access the third item in the original array. And since this returns an array of references, modifying that will also modify the element of the original array.

Upvotes: 1

Related Questions