53

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'?

3
  • 2
    What language? I see one answer that appears to be assuming Perl, and one that's assuming PHP. Commented Jun 4, 2010 at 0:39
  • 1
    If it is PHP you might want to read: php.net/manual/de/language.types.array.php Commented Jun 4, 2010 at 0:40
  • 1
    Yes, it's PHP. Thanks for the link.
    – JEagle
    Commented Jun 4, 2010 at 0:50

2 Answers 2

112

It's as simple as this :

$array[$key];
0
33

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
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.