PHP Shorthand: Using Ternary Operators (?:) instead of If-Else Statements

May 22nd, 2011 by Tony de Jesus

All programmers need to agree with me when I say: One of the most used and most important parts of our code are the if-else statements. No matter what the programming language, we can’t avoid the comparisons. We need to check if a variable is set or if it stores a specific value. if-else statements are useful, easy to read and understand. However, they can be too long.

PHP gives us the possibility to reduce our lines of code by using ternary operators. Ternary operators are shortcut comparison operators that replace if-else statements in a PHP script.  In order to use ternary operators, the only thing that you need to do is to respect the structure: (condition) ? (value if true) : (value if false).

For example, you can write the following if-else statement:


if($food == "spaghetti"){
     $message = "Oh yeah!";
}
else{
     $message = "Oh no!";
}

Of this way by using ternary operators:


$message = ($food == "spaghetti") ? "Oh yeah!" : "Oh no!";

That’s it! One single line.

Related posts

,

 
 
 

2 Comments

  1. Duarte

    Nice article!
    To be honest i tend to use always the if and else statements, next time i will try to use your suggestion!! :)

  2. I liked your article is an interesting technology
    thanks to google I found you

Trackbacks

Leave a Reply