tags:

views:

59

answers:

2

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

+4  A: 

It's as simple as this :

$array[$key];
HoLyVieR
Aahhhhh...the beauty of association.
Babiker
Thanks. It worked.Need to learn a bit more.thanks
JEagle
+2  A: 

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
Mark Rushakoff
Thanks. It was in PHP. thanks a lot.
JEagle