samedi 29 août 2015

How to limit value assignment in foreach?

Here is my array and foreach:

$colors = array("red", "green", "blue", "yellow"); 

foreach ($colors as $value) {
    echo "$value <br>";
}

I need to just assign only the first three keys and I want this output:

red
green
blue

I can do that like this:

$i=1;
foreach ($colors as $value) {
    if ($i=4){break;}
    echo "$value <br>";
    $i++;
}

But I think using a if() statement in a loop (in reality my array has more than 100 elements) is not optimized, so there is any better approach for doing that ?

Aucun commentaire:

Enregistrer un commentaire