1

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>'; 
1
  • 1
    This really should not be written in 2 lines. Commented Apr 23, 2010 at 0:49

6 Answers 6

8

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>';
Sign up to request clarification or add additional context in comments.

Comments

2
  • 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.

Comments

1

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.
}

}

2 Comments

I don't think he wants a nested loop.
Yup, instead of reading what he was actually doing. I read what he wrote (2 variables).
1

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>';
    }
}

Comments

1

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.

Comments

1

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) {

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.