user6266762
user6266762

Reputation:

how to get particular value in array PHP

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

Upvotes: 1

Views: 1245

Answers (3)

Wee Zel
Wee Zel

Reputation: 1324

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])

Upvotes: 0

Sebastian Tkaczyk
Sebastian Tkaczyk

Reputation: 372

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.

Upvotes: 0

B.Mossavari
B.Mossavari

Reputation: 129

You may get it this way

$value = $countries[$country_code];

Upvotes: 3

Related Questions