Reputation: 169
I'm looking for a solution to check an array if country-code exists. And than post the whole name.
I'm new in PHP so I'm not shure if in_array is the right way :)
The php code
$country = "al"
<?php if (in_array("$country", $countries_en)) {
echo "$country"; }
?>
So the echo what i want is not "al". I want "Albania".
The array:
$countries_en = array
(
'ad' => 'Andorra',
'ae' => 'United Arab Emirates',
'af' => 'Afghanistan',
'ag' => 'Antigua and Barbuda',
'ai' => 'Anguilla',
'al' => 'Albania',
'am' => 'Armenia,..... and much more
Upvotes: 0
Views: 713
Reputation: 5500
Try array_walk
function:
$country = 'ai';
$countries_en = array(
'ad' => 'Andorra',
'ae' => 'United Arab Emirates',
'af' => 'Afghanistan',
'ag' => 'Antigua and Barbuda',
'ai' => 'Anguilla'
);
array_walk($countries_en, function($value,$key) use ($country) {
if ($country === $key) {
echo $value; // result "Anguilla"
}
});
Upvotes: 1
Reputation: 35
As a solution to your problem please try executing following code snippet
<?php
$country='al';
if(isset($countries_en[$country]))
{
echo $countries_en[$country];
}
?>
Upvotes: 1
Reputation: 219884
Just use $country
as the key to get the value you want from the $country_en
array:
$country = "al";
if (array_key_exists($country, $countries_en)) {
echo $country_en[$country];
}
You want to use array_key_exists()
here, not in_array()
as al
is one of the array keys, not a value.
Upvotes: 3
Reputation: 3425
Try this:
Here "al" is used as key of array, not value and in_array() function checks for value.
So, you need to use another function array_key_exists() here.
<?php if (array_key_exists($country, $countries_en)) {
echo $country_en[$country]; }
?>
Upvotes: 2