bobbybackblech
bobbybackblech

Reputation: 1886

Loop only through specific array

I have the following array

$array = array("Farbe" => array("blau", "rot", "grün"),
               "Größe" => array("klein", "mittel", "groß"));

The order is random, so "Farbe" could be the first array but "Größe" could also be the first array.

In my foreach i want only the array with "Farbe". How can i tell my foreach to only loop through the "Farbe" array?

Upvotes: 0

Views: 50

Answers (3)

user2684521
user2684521

Reputation: 380

Here are two ways depending on what you want to do.

foreach($array['Farbe'] as $key){
    //code goes here
}

If you needed to do something with that data in your html like adding it to a table you could do something like this.

<table>
<?php foreach($array['Farbe'] as $key):?>
    <tr>
        <td><?php echo $key; ?></td>
    </tr>
<?php endforeach; ?>
</table>

Upvotes: 1

Chizzle
Chizzle

Reputation: 1715

$farbeArray = $array['Farbe'];
foreach($farbeArray as $value){
    echo $value;
}

Upvotes: 1

taxicala
taxicala

Reputation: 21759

You can access by key to the array and then loop it:

foreach($array['Farbe'] as $farbe) {
    //Do something with $farbe.
}

Upvotes: 3

Related Questions