Increment variable within a foreach

Asked

Viewed 1,825 times

2

How do I make a variable increment within a foreach?

foreach($adults as $adultos):
    $i = 1;
    echo "<strong>Quarto".$i++."</strong><br>";
    echo "Adultos:".$adultos."<br>";
endforeach;
  • 1

    Declare her out of the loop.

  • She’s incrementing normally on the first line echo. The real problem is that you restart it every iteration.

2 answers

4


Yes, just leave the variable setting out of the loop:

$i = 1;

foreach($adults as $adultos):
    echo "<strong>Quarto".$i++."</strong><br>";
    echo "Adultos:".$adultos."<br>";
endforeach;

Otherwise, at each loop iteration the variable is reset to the initial value 1.

If your array for sequential, i.e. non-associative, you won’t even need the control variable $i, because the key itself ends up playing that role:

foreach($adults as $i => $adultos):
    echo "<strong>Quarto".($i+1)."</strong><br>";
    echo "Adultos:".$adultos."<br>";
endforeach;

In this case I used $i+1 because the content of array starts at 0.

And the third option is using the loop for, as quoted in maniero’s response.

  • Thank you very much, you helped me a lot!

3

You can just take off the loop startup:

$adultos = array( "a", "b", "c" );
$i = 1;
foreach ($adultos as $adulto):
    echo "<strong>Quarto " . $i++ . "</strong><br>";
    echo "Adultos: " . $adulto . "<br>";
endforeach;

Or you can do the most appropriate thing in this case which is to use the for normal:

for ($i = 0; $i < count($adultos); $i++) {
    echo "<strong>Quarto ". ($i + 1) ."</strong><br>";
    echo "Adultos: " . $adultos[$i] . "<br>";
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.