user1871245
user1871245

Reputation:

Can I specify which key I want in a foreach loop?

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

Answers (3)

Kamil
Kamil

Reputation: 1641

Upvotes: 0

user1386320
user1386320

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

Explosion Pills
Explosion Pills

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

Related Questions