tags:

views:

72

answers:

6

I'm trying to loop 2 variables and with an output that looks like this '91 - 96 lbs' I can get the For statement to work with just one variable but with two it does not work.

for ($k = 91; $k <= 496; $k=$k+4($i = 96; $i <= 500; $i=$i+4))  
echo '<option value='.$k. ' - ' .$i. ' lbs'("<%m_weight%>" == .$k. ' - ' .$i. ' lbs' ? ' selected="selected"' : '').'>'.$k. ' - ' .$i. ' lbs</option>'; 
A: 

You will need to nest your for loops. That syntax is incorrect

for ($k = 91; $k <= 496; $k=$k+4)
{
for($i = 96; $i <= 500; $i=$i+4)
{
//more code here.
}

}

DTown
I don't think he wants a nested loop.
SLaks
Yup, instead of reading what he was actually doing. I read what he wrote (2 variables).
DTown
+8  A: 

You probably don't actually want two variables there:

for ($k = 91; $k <= 496; $k=$k+5)
  echo '<option value='.$k. ' - ' .($k+4). ' lbs'("<%m_weight%>" == .$k. ' - ' .($k+4). ' lbs' ? ' selected="selected"' : '').'>'.$k. ' - ' .($k+4). ' lbs</option>';
Ignacio Vazquez-Abrams
A: 

You need to nest them correctly:

for ($k = 91; $k <= 496; $k=$k+4) {
    for ($i = 96; $i <= 500; $i=$i+4) {
        echo '<option value='.$k. ' - ' .$i. ' lbs'("<%m_weight%>" == .$k. ' - ' .$i. ' lbs' ? ' selected="selected"' : '').'>'.$k. ' - ' .$i. ' lbs</option>';
    }
}
masher
why the downvote? His original code reads as if he wants to nest his loops...
masher
+1  A: 

No need for two for loops, or two variables at all:

for ($k = 91; $k <= 496; $k=$k+5)
    echo '<option value='.$k. ' - ' .($k+4). ' lbs'.($m_weight == $k ? ' selected="selected"' : '').'>'.$k. ' - ' .($k+4). ' lbs</option>';

Check what format $m_weight is in; your syntax there was garbled.

Nicholas Wilson
+2  A: 
  • you don't need two variables, one would be enough

  • if you really, really, really want two variables, just use coma to separate statements and logical operators to combine tests.

    for ($k = 91, $i = 96 ; ($k <= 496) || ($i <= 500) ; $k=$k+4, $i= $i + 4) { echo "$k - $i lbs"; }

As you can see the end test now looks quite silly (both parts of the test become true at the same time)... that's one more hint that you didn't really wanted two variables at all.

kriss
+1  A: 

You can put multiple operations in the initialization and increment portion of a for loop using a ,

for ($k=91, $i=96; $k<=496 && $i<=500; $k+=4, $i+=1) {

}
gnarf