jingleboy99 jingleboy99 - 5 months ago 9
PHP Question

Php for loop with 2 variables?

is it possible to do this? (here is my code)

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


I want something like this:

var 0 is 10

var 1 is 9

var 2 is 8 ...

But my code is wrong, it gives a huge list. Php guru, help me !!

Answer

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.