How to calculate a FOR for every 6 increments does it echo?

0

I have a simple FOR that I need every 6 increments to send an echo with a message, follows code:

$carros = array("Volvo", "BMW", "Toyota", "Alfa Romeu", "WV", "Teste", "test2", "Teste4", "Teste3", "Teste5", "Volkswagem", "Ferrari");

for ($i=0; $i < count($carros); $i++) {
    echo "Carro ".$carros[$i];

    //quando chegar a 6, 12, 18, 24, 30... ele manda esse echo
    echo "Página: ".$i;

}
    
asked by anonymous 18.10.2018 / 21:54

3 answers

8

place an IF with a condition checking to see if your counter is a multiple of 6.

$carros = array("Volvo", "BMW", "Toyota", "Alfa Romeu", "WV", "Teste", "test2", "Teste4", "Teste3", "Teste5", "Volkswagem", "Ferrari");

for ($i=0; $i < count($carros); $i++) {
    echo "Carro ".$carros[$i];

    if ($i%6 === 0){
      echo "Página: ".$i;
    }
}
    
18.10.2018 / 21:57
4
$carros = array("Volvo", "BMW", "Toyota", "Alfa Romeu", "WV", "Teste", "test2", "Teste4", "Teste3", "Teste5", "Volkswagem", "Ferrari");

for ($i=0; $i < count($carros); $i++) {
echo "Carro ".$carros[$i];

$number = 0;
if($i === (6 + number)){
    number = number + 6;
    echo "Página: ".$i;
 }
}
    
18.10.2018 / 22:01
3

You can check that $i is mod (which checks if the division has no rest) of 6 then print the page number.

if($i % 6 === 0) echo $i;

Another simple example:

foreach(range(1, 60 ) as $item){
    if($item % 6 === 0) echo 'Página '. $item .PHP_EOL;
}

Output:

Página 6
Página 12
Página 18
Página 24
Página 30
Página 36
Página 42
Página 48
Página 54
Página 60

Example - ideone

    
18.10.2018 / 21:59