Adam Strudwick
Adam Strudwick

Reputation: 13129

PHP "for" loop issue

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)

Upvotes: 1

Views: 115

Answers (3)

Jeffrey04
Jeffrey04

Reputation: 6338

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

Upvotes: 4

Luchian Grigore
Luchian Grigore

Reputation: 258548

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

or

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

Upvotes: 4

hakre
hakre

Reputation: 197624

$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).

Upvotes: 13

Related Questions