Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do print and echo behave differently in a "for" loop [duplicate]

If I use print in this code:

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

I see as output this:

2

3

4

But when I use echo the code doesn't work:

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

I see this error:

PHP Parse error: syntax error, unexpected 'echo' (T_ECHO), expecting ')' in /media/datos/xampp/htdocs/temp/1.php on line 3

My question is:

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

References:

  • http://php.net/echo
  • http://php.net/print
like image 482
Adrian Cid Almaguer Avatar asked Jun 08 '15 17:06

Adrian Cid Almaguer


1 Answers

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

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

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

see this answer: https://stackoverflow.com/a/234255/1848929

What about echo:

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

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

like image 169
hakkikonu Avatar answered Oct 14 '22 18:10

hakkikonu