1

Simple question:

Why is this:

 for($k=1;$k<=10;$k+2) { }

giving an infinite loop? When I change $k+2 by $k++, it works fine.

How can I correct it? (I can't change the 10 for an impair number because I need this function to work either with a pair or impair value at that place)

2
  • @Shef $k will always be 1 in this case because $k is not updated Commented Aug 15, 2011 at 6:54
  • You are both right, just got up, such an early thought... :) Commented Aug 15, 2011 at 7:00

3 Answers 3

13
$k+2

This won't change $k's value, so it never get's higher than 10. Probably you meant:

$k+=2

Which will increase $k by two each time the expression get's evaluated (at the end of each for-loop).

Sign up to request clarification or add additional context in comments.

Comments

4
 for($k=1;$k<=10; $k = $k+2) { }

or

 for($k=1;$k<=10; $k += 2) { }

Comments

4

it is infinite loop because $k is not updated, try this instead

for($k = 1; $k <= 10; $k = $k + 2) {}

or

for($k = 1; $k <= 10; $k += 2) {}

Reference: PHP operators

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.