Reputation:
If I have an array called $animalarray
with keys dog
, cat
, bird
, can I specify which key I want to use in a foreach loop?
I'm doing something like this right now but it just returns all the values from the array
foreach($animalarray as $species=>$bird)
{
echo $bird;
}
I'd like this to only echo out the value under the key Bird, but this returns all values under all the keys.
Upvotes: 1
Views: 64
Reputation: 1641
Upvotes: 0
Reputation:
Do it like this:
$allowedKeys = array('dog');
foreach($animalarray as $species=>$bird)
{
if(array_key_exists($species, $allowedKeys)) {
echo $bird;
}
}
It will output matches only for dogs.
Upvotes: 1
Reputation: 191739
Why don't you just do echo $animalarray['bird'];
?
You could also do this, but it's unnecessary:
foreach($animalarray as $species=>$bird) {
if ($species == 'bird') {
echo $bird;
}
}
Upvotes: 4