简体   繁体   中英

Find the value of a key from an array in PHP

I have this array in PHP:

Array
(
    [en-CA] => English
    [fr-CA] => Français
    [es-ES] => Español
)

I would like to get the language name from the key.

So I made this but it doesn't work:

$lang = "en-CA";
$curLang = array_search($lang, $languages);

$curLang returns me nothing.

Thanks.

array_search — Searches the array for a given value and returns the first corresponding key if successful

You are actually searching for a key, not a value.

So you can just do this to get the value you want.

$curLang = $languages[$lang];

Try this:

$languages =   Array
   (
     [en-CA] => English
     [fr-CA] => Français
     [es-ES] => Español
  )

 $lang = "en-CA";
 $curLang = $languages[$lang];

You can searching for a key, not a value.

<?php
$languages = array(

    'en-CA' => 'English',
    'fr-CA' => 'Français',
    'es-ES' => 'Español',
);  

$lang = "en-CA";
if (array_key_exists($lang, $languages)) {
  echo $languages[$lang];
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM