Increment variable inside a foreach [closed]

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;
    
asked by anonymous 19.09.2017 / 01:51

2 answers

3

Yes, you just have to leave the variable definition outside the loop:

$i = 1;

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

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

If your array is sequential, i.e. non-associative, you will not even need the control variable $i , since 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 array index starts at 0.

And the third option is to use the for loop, as quoted in the bigown answer . p>     

19.09.2017 / 01:54
3

You can only take the initialization of the loop:

$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 in this case which is to use for normal:

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

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

    
19.09.2017 / 01:57