Latox
Latox

Reputation: 4705

how to do this.. backwards?

I currently have:

$i = 1;
while {
  echo $i;
  $i++;
}

And it shows:

1
2
3
4 etc..

How would I make it display backwards?

For example

4
3
2
1 etc..

I basically want to do the exact same thing but flip it around.

Upvotes: 9

Views: 18954

Answers (4)

Akash Sethi
Akash Sethi

Reputation: 324

If you want to back-word sr number as per your count of rows in result then use this.

$num_rows = mysqli_num_rows($query);

$x = $num_rows;

$x--;

Upvotes: 2

01001111
01001111

Reputation: 836

$i = 4;
while($i > 0) {
  echo $i--;
}

Upvotes: 0

Jan Sverre
Jan Sverre

Reputation: 4723

$i = 10;
while($i>0) {
  echo $i;
  $i--;
}

Upvotes: 16

rofyg
rofyg

Reputation: 91

Example - Print number through 0 to 5 with PHP For Loop

for($i=0; $i<=5; $i=$i+1)
{
    echo $i." ";
}

In the above example, we set a counter variable $i to 0. In the second statement of our for loop, we set the condition value to our counter variable $i to 5, i.e. the loop will execute until $i reaches 5. In the third statement, we set $i to increment by 1.

The above code will output numbers through 0 to 5 as 0 1 2 3 4 5. Note: The third increment statement can be set to increment by any number. In our above example, we can set $i to increment by 2, i.e., $i=$i+2. In this case the code will produce 0 2 4.

Example - Print number through 5 to 0 with PHP For Loop

What if we want to go backwards, that is, print number though 0 to 5 in reverse order? We simple initialize the counter variable $i to 5, set its condition to 0 and decrement $i by 1.

for($i=5; $i>=0; $i=$i-1)
{
    echo $i." ";
}

The above code will output number from 5 to 0 as 5 4 3 2 1 0 looping backwards.

Good luck! :)

Upvotes: 7

Related Questions