views:

839

answers:

4

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

+13  A: 

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.

Gumbo
+1 - didn't even know you could do this!
John Rasch
Oh wow. I had no idea you set multiple vars within a for-loop. Nice.
Jonathan Sampson
Given what the syntax of a for loop means, it makes sense...
Thomas Owens
My next question: can you do this in C, C++, Java, and C#?
Thomas Owens
@Thomas, yes. C++ and C# definitely, and I'm pretty sure about C and Java, but I try to avoid it as it can get unreadable fast.
Sean Nyman
Thanks, works 100%
jingleboy99
There are only rare occasions where I would want to use it, but I'm totally putting this one in my toolbelt.
Thomas Owens
This works in C as well.
Graeme Perrow
According to someone I know, it does indeed work in Java.
Thomas Owens
Thanks for this code snippet. Didn't think that you could do something like this...
+1  A: 

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.

AlbertoPL
In fact it’s 11·11=121 (from 0 to 10 inclusive).
Gumbo
Ah, yes, didn't even see that.
AlbertoPL
A: 

To expand on the other (correct) answers, what you were doing is called nesting loops. This means that for every iteration of the outer loop (the first one), you were completing the entire inner loop. This means that instead of 11 outputs, you get 11 + 11 + 11 + ... = 11 * 11 outputs

Sean Nyman
+1  A: 

If, as your code looks like, you have two values running the opposite direction you could simply substract:

echo "Var " . $i . " is " . 10 - $i . "<br>";

But I guess that's not really what you want? Also, be careful with the suggested comma operator. While it is a nice thing it can cause naughty side effects in other languages like C and C++ as PHP implements it differently.

bluebrother