How to find array / dictionary value using key?

PhpArraysKey

Php Problem Overview


I would like to find the value in an array using the key.

Like this:

$array=('us'=>'United', 'ca'=>'canada');
$key='ca';

How can I have the value 'canada'?

Php Solutions


Solution 1 - Php

It's as simple as this :

$array[$key];

Solution 2 - Php

It looks like you're writing PHP, in which case you want:

<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>

Notice that the ('us'=>'United', 'ca'=>'canada') needs to be a parameter to the array function in PHP.

Most programming languages that support associative arrays or dictionaries use arr['key'] to retrieve the item specified by 'key'

For instance:

###Ruby

ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
 => {"us"=>"USA", "ca"=>"Canada"} 
ruby-1.9.1-p378 > h['ca']
 => "Canada" 

###Python

>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'
C#
class P
{
    static void Main()
    {
        var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
        System.Console.WriteLine(d["ca"]);
    }
}
Lua
t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJEagleView Question on Stackoverflow
Solution 1 - PhpHoLyVieRView Answer on Stackoverflow
Solution 2 - PhpMark RushakoffView Answer on Stackoverflow