Echo, Print and the Conditional Operator

11 12 2010

Octeract Petrie polygon ternary Boolean connec...

Image by Cuito Cuanavale via Flickr

Most of the time the PHP built-ins echo and print are interchangeable in terms of outputting values to the browser window(1). But they do have nuances which may come in handy.  Print is a one-for-one deal, that is it takes only one argument and it returns a value of 1 always, rain or shine.  Echo on the other hand, can output more than one argument if you separate each one with a comma but it returns no value at all.

Where these differences really matter is when you use a conditional operator.  Depending on where you use either print and/or echo, your choice of which to use may enhance your code or break it.

Here’s an example whose style is admittedly unsuitable for the enterprise; the code suffers from a blatant lack of clarity. The online manual says that one should refrain from stacking ternary operators but I happily do so with the following snippet to show the differences between the two built-ins.

<?php
$clrs = array('r'=>'red', 'b'=>'blue');
$color = $clrs["b"];

echo "Love is ",  
  (print !(print (
    print ( ($color == "blue") ? 
      print "{$clrs['b']} ? " : print "{$clrs['r']} ? ")? 
                               "true" : "false")?
                               " (1) " : "")?: 24)? 
                               'x7' : ' hours';

/** Result:
     Love is blue ? true (1) 24x7
 
     IN: PHP5.3-PHP7; (See http://3v4l.org/IF9Sk)
**/

The way to tackle the above code is to recall that PHP’s ternary operator is a little weird, since it is left-associative instead of right-associative like most ternary operators in other languages. So, start with the very first expression followed by a question mark, i.e. ($color == ‘blue’)? which displays “love is blue” when true and print returns a value of 1. In fact, whether $color’s value, print always returns 1, which makes the overall value of that expression 1. This result causes the next print command to display “true” and return 1, too. Now when that expression evaluates and its result is a true, so the expression takes on the value of 1 and “(1)” displays. To have some more fun, I mischievously apply the ! operator on that expression negating its value so that the expression renders false. That comes in handy as I use the conditional operator ?: (first appearing in PHP5.3) which short-cuts matters. Since the expression is false, it takes on the value of 24. Again, I use print to display the information, so it returns 1 as the expression’s value for use by echo. Echo has two arguments, the first being the string “Love is” while the second is an expression used in yet another ternary expression whose true result concludes this exercise by displaying string x7 .

So, to recap, echo and print will both oblige with displaying information. If you need to display more than one piece of data, you may prefer to use echo as it can take multiple comma-separated arguments. Both echo and print can be used also in ternary or conditional expressions. The main difference is that in these situations echo can only be used to display data, whereas print can return a value so that you may use it to display data as well as to imbue an expression with a value of 1.

You may find the following links of interest if you wish to read more about echo vs. print:
http://www.learnphponline.com/php-basics/php-echo-vs-print

http://bytes.com/topic/php/answers/12487-echo-vs-print

1. If speed is your main concern, one might think that print would be slower since it has to output a value as well as return a boolean. Surprisingly, print may be faster than echo in some situations. In a commentary of 2009, Gwynne Raskind, states that the way PHP is configured may effect echo’s performance, causing it to be slower than print. She also indicates that in some cases the speed of echo and print may even be equal. (See http://groups.google.com/group/make-the-web-faster/browse_thread/thread/ddfbe82dd80408cc).

This work is licensed under a Creative Commons License
.

Advertisements

Actions

Information

3 responses

11 12 2010
John

Sharon,
Thanks again for the work you do here; it’s appreciated.

Have a Happy Holidays,

John

14 01 2011
William Estrada

Good article. I personally got in the habit of using print for all user output while I use echo for output for debugging.

17 01 2011
Sharon Lee Levy

William,

Thanks for browsing — glad you liked the article. Interesting how you differentiate between when to use print and when to use echo.

— Sharon

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: