TIL: The Compact Ternary Operator in PHP

An extremely useful tool in nearly any language is the ternary operator. A completely useless example:

$var = "hello";

echo $var == "hello" ? $var : "goodbye";

Just now, my good friend Zach Badgett, let me know about PHP’s (as of 5.3) so-called ‘compact’ ternary operator. It lets you leave out the first parameter:

echo $var == "hello" ?: "goodbye";

 

It is semi-useful, I suppose. Something I’d like to see is an implementation of something similar to MySQL’s IFNULL. To avoid using undefined variables or indexes, I use this type of snippet often:

echo empty($var) ? "" : $var;

It would be extremely nice if I could cut that down to a single function call, however, even writing a function to do the above has issues. For example, when you pass an object that utilize magic methods, you get all kinds of issues. This happens even when passing-by-reference.

It seems, for now, I’ll have to stick with the expanded ternary operator.

 

  1. Спасибо. Прочитал с интересом, и вообще полезный у Вас блог

Leave a Comment

:) :? 8) ;( 8O :evil: :fat: :D ^_^ :x :| :paint: :p :$ :roll: :( :slim: :o :twisted: ;) :yell: :arrow: :?: :idea: :heart:

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>