1

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.

4

3 回答 3

4

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;
    }
}
于 2013-03-13T00:19:56.427 回答
1

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.

于 2013-03-13T00:21:45.780 回答
0
于 2013-03-13T00:24:09.867 回答