How to calculate a FOR for 6 in 6 increments it give an echo?

Asked

Viewed 75 times

0

I have a simple FOR that I need that every 6 increments it sends 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;

}

3 answers

8


place an IF with a condition checking 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;
    }
}
  • send code examples...

  • I edited the answer, using your own FOR logic and adding the if with the check. Making a 'MOD' of the counter value with 6, if the result is 0, means that the number is multiple of 6, and so will print the sequence you want. @Alanps

3

Can you check whether the $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;
}

Exit:

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

3

$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;
 }
}

Browser other questions tagged

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