Php for loop with 2 variables? Php for loop with 2 variables? php php

Php for loop with 2 variables?


Try this:

for ($i=0, $k=10; $i<=10 ; $i++, $k--) {    echo "Var " . $i . " is " . $k . "<br>";}

The two variables $i and $k are initialized with 0 and 10 respectively. At the end of each each loop $i will be incremented by one ($i++) and $k decremented by one ($k--). So $i will have the values 0, 1, …, 10 and $k the values 10, 9, …, 0.


You could also add a condition for the second variable

for ($i=0, $k=10; $i<=10, $k>=0 ; $i++, $k--) {    echo "Var " . $i . " is " . $k . "<br>";}


You shouldn't be using two for-loops for what you'd like to achieve as you're looping 121 times total (11x11). What you really want is just to have a counter declared outside of the loop that tracks j, and then decrement j inside the loop.

Edit: Thanks Gumbo for catching the inclusion for me.