Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !!

like image 309
jingleboy99 Avatar asked Jul 23 '09 15:07

jingleboy99


2 Answers

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.

like image 182
Gumbo Avatar answered Oct 02 '22 17:10

Gumbo


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>"; } 
like image 38
Mihail Minkov Avatar answered Oct 02 '22 15:10

Mihail Minkov