Find array value using key

后端 未结 2 1433
青春惊慌失措
青春惊慌失措 2020-12-08 06:09

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

like this:

$array=(\'us\'=>\'United\', \'ca\'=>\'canada\');
$key=\'ca\';
相关标签:
2条回答
  • 2020-12-08 06:53

    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 讨论(0)
  • 2020-12-08 07:13

    It's as simple as this :

    $array[$key];
    
    0 讨论(0)
提交回复
热议问题