-5

Consider the following simple code snippet:

<!DOCTYPE html>
    <html>
        <body>

            <?php
                $x = 5;
                $y = 4;    

                echo print $x + $y;
            ?>

        </body>
    </html>

The output is below :

91

Now consider the other similar code snippet:

<!DOCTYPE html>
    <html>
        <body>

            <?php
                $x = 5;
                $y = 4;

                print echo $x + $y;
            ?>

        </body>
    </html>

The output is below :

*a blank white screen*

Why so?

If echo and print can be used in a one statement why can't the reverse pattern works?

Please satisfy my query with good explanation.

Thanks.

6006604
  • 7,577
  • 1
  • 22
  • 30
PHPLover
  • 1
  • 51
  • 158
  • 311
  • @JohnConde:My intention is towards clearing the concept and not giving any importance to the output. The output is just immaterial in this case. I want to clear the concept only. – PHPLover Sep 23 '15 at 12:59
  • Look at the docs for [print](http://php.net/manual/en/function.print.php) and [echo](http://php.net/manual/en/function.echo.php). print returns an _int_ and echo doesn't return anything. – Jeff Lambert Sep 23 '15 at 12:59
  • @watcher: I already knew that. I want to clear my doubt why they can't be used interchangeably? – PHPLover Sep 23 '15 at 13:00
  • `echo` is a language statement, and `print` an unary expression. – mario Sep 23 '15 at 13:02
  • what version of PHP? when I try on PHP 5.5.12 `print echo 12 + 3;` I get `syntax error, unexpected 'echo'` – Jeff Lambert Sep 23 '15 at 13:02
  • @watcher:I'm using PHP 5.5.29(The latest stable version of series 5.5) – PHPLover Sep 23 '15 at 13:04
  • @mario:Could you please explain me what does exactly mean by unary expression? Could you please put more focus on your concepts? – PHPLover Sep 23 '15 at 13:05
  • 6
    Pick your duplicate: http://stackoverflow.com/questions/1647322/whats-the-difference-between-echo-print-and-print-r-in-php, http://stackoverflow.com/questions/234241/how-are-echo-and-print-different-in-php, http://stackoverflow.com/questions/7094118/reference-comparing-phps-print-and-echo – mario Sep 23 '15 at 13:09

1 Answers1

3

print is a construct that behaves like a function; it has a return value of 1. Therefore:

echo print 'x';

is syntactically valid and produces x1, where x is printed by print and 1 by echo. This is equivalent to:

$print_value = print 'x';
echo $print_value;

echo, on the other hand, has no return value, so $echo_value = echo 'x'; is a syntax error and so is print echo 'x';.

lafor
  • 12,472
  • 4
  • 32
  • 35