Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Loop do action for each 10, 20, 30 etc [duplicate]

In php i have loop e.g.

for ($i = 0; $i <= 1000; $i++) {
   if ($i = 10 || $i == 20 || $i == 30 || $i == 40 || $i == 50 || $i == 60) {
      echo $i;
   }
}

imagine i need to echo $i every 10,20,30,40,50,60,..970,980,990 there should be way to not write 100 conditions in if statement. Is there some logical way to see if $i increased by 10 then do something like:

if ($i == $i+10) {
   ...
}

P.S. if possible i dont want to introduce another variable to count i need to find solution with using only $i

like image 700
JohnA Avatar asked May 17 '12 17:05

JohnA


People also ask

What are the 4 PHP loop types?

A Loop is an Iterative Control Structure that involves executing the same number of code a number of times until a certain condition is met.

How does PHP foreach loop work?

PHP foreach loop is utilized for looping through the values of an array. It loops over the array, and each value for the fresh array element is assigned to value, and the array pointer is progressed by one to go the following element in the array.

How can I print 1 to 10 numbers in PHP?

We can print numbers from 1 to 10 by using for loop. You can easily extend this program to print any numbers from starting from any value and ending on any value. The echo command will print the value of $i to the screen. In the next line we have used the same echo command to print one html line break.


2 Answers

Try:

if ($i % 10 == 0) 

That will trigger whenever your index is exactly divisible by 10.

like image 94
andrewsi Avatar answered Sep 20 '22 23:09

andrewsi


rewrite your for loop to:

for ($i = 0; $i <= 1000; $i+=10) {

And I don't know whether it worked for you with commas like this (as in your initial post):

for ($i = 0, $i <= 1000, $i++) {
like image 34
Alexey Avatar answered Sep 20 '22 23:09

Alexey