1

i wanted to get particular value from array .

$countries = array("af"=>"Afghanistan","ax"=>"Aland Islands","al"=>"Albania);"

And i have value in variable

$country_code="ax";

Using this variable i want to get array value from array

i am new to php ,thank you

1
  • For php7, you can use $countries[$country_code]??null, this will return null if there isn't one in the array. Commented Aug 26, 2017 at 8:31

3 Answers 3

3

You may get it this way

$value = $countries[$country_code];
Sign up to request clarification or add additional context in comments.

Comments

0

According to php documentation:

Array elements can be accessed using the array[key] syntax.

In your code it will looks like: $value = $countries[$country_code];

Also I recommend you to read about arrays in PHP here: http://php.net/manual/en/language.types.array.php your case is explained in 6th example.

Comments

0

just to expand on @B.Mossavari answer, you should check the key is there before extracting the value or PHP will return a undefined index Notice

if (array_key_exists($country_code, $countries)) {
    $value = $countries[$country_code];
} else {
    $value = ''; // set value to something so your code doesn't fail later 
}

this is my preferred way, but you could also check using isset($countries[$country_code]) or !empty($countries[$country_code])

1 Comment

A better way of doing it is like this $value = (array_key_exists($country_code, $countries)) ? $countries[$country_code] : ''

Your Answer

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