DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

PHP Shorthand Syntax

04.08.2005
| 57861 views |
  • submit to reddit
        Handy shorthand syntax for php. From: http://www.tech-recipes.com/php_programming_tips288.html


A compact (if cryptic) shorthand is useful: 

echo "var is ".($var < 0 ? "negative" : "positive"); 

is equivalent to: 

echo "var is "; 
if ($var < 0) 
    echo "negative"; 
else 
    echo "positive"; 

The shorthand can be considered (expression ? true_value : false_value) where 'expression' is evaluated and, if true, the 'true_value' is returned, otherwise the 'false_value' is returned.



    

Comments

Snippets Manager replied on Mon, 2012/05/07 - 2:11pm

If the ternary operator (aka ?:) has its performance costs. To make high-performant PHP, the longer-winded version wins, according to Ilya's talk at EZ in Norway. Ilya's talks page links to the talk.