I...">

Why print and echo behave differently in the for loop

If I use print in this code:

 <?php for($i = 1; $i <= 3; print $i . "\n") { $i++; } ?> 

I see the output of this:

2

3

4

But when I use echo , the code does not work:

 <?php for($i = 1; $i <= 3; echo $i . "\n") { $i++; } ?> 

I see this error:

PHP password error: syntax error, unexpected "echo" (T_ECHO) waiting ")" in / media / datos / xampp / htdocs / temp / 1.php on line 3

My question is:

  • Why can I use print as the third expression in the for loop, but I cannot when using echo and why do they behave differently from each other?

Literature:

+7
php for-loop printing echo behavior
source share
1 answer

Expression. print () behaves like a function you can do: $ ret = print "Hello World"; And $ ret will be 1. This means that printing can be used as part of a more complex expression, where echo cannot. example from the PHP manual:

 $b ? print "true" : print "false"; 

Some of my answer is part of the answer below. I think this is the answer to your question. The most important part of print() behaves like a function

see this answer: fooobar.com/questions/9187 / ...

How about echo :

Note: Since this is a language construct, not a function, it cannot be called using variable functions.

see notes on this page: http://us2.php.net/manual/en/function.echo.php

+6
source share

All Articles