0

Example 1

for($var=1;$var<=5;print $var,$var++); //valid

Example 2

for($var=1;$var<=5;echo $var,$var++); //invalid

the behavior of above two statements is not that straight, could any body explain why they are showing different results ?

X-Pippes
  • 1,170
  • 7
  • 25
bajajsahil
  • 66
  • 3

2 Answers2

5

echo is a language construct, not a function. It has no return value. print() is a function, and DOES have a return value.

Ref: http://php.net/echo http://php.net/print

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • `print()` is also a language construct, but I assume that because `echo`'s syntax allows `echo 1, 2, 3` to output `123` which conflicts with the syntax for a loop declaration, so it's disallowed. – Sammitch Oct 24 '13 at 17:58
  • but it behaves as a function, because it has a return value. But yeah, probably that's it. the loop runs because $var++ will still increment, but echo will snag the `,` for itself. – Marc B Oct 24 '13 at 17:59
  • But it's not a runtime error, it's a parse error. ;) – Sammitch Oct 24 '13 at 18:01
0

While both print and echo are language constructs, the syntax defined for echo conflicts with what you are doing. Specifically:

echo 1, 2, 3, 4;
//output: 1234

This conflicts with the syntax for a loop definition, which is why I believe you're not permitted to use echo there.

Sammitch
  • 30,782
  • 7
  • 50
  • 77