Skip to main content

Using Ternary Operators in PHP

Member for

2 years 2 months
Submitted by admin on

The use of ternary operators in PHP is fantastic and even though I always forget to add the : when writing a ternary operator it is great to have in the arsenal when writing some PHP. As a complement to an if else statement when used in the appropriate way can really assist in PHP development and should not be over looked. I always like to use it when an if else or if statement will fit on one line. If you want to know more about the ternary operator go to php.net. There are real advantages of using a ternary operator when coding,

  1. It makes your PHP code easier to read.
  2. Using a ternary operator creates more compact code.
  3. Maintaining your code becomes faster.
  4. It is easier to find bugs in your software (most of the time).

What does a ternary operator look like in PHP?

In the example below the ternary operator is testing to see if the number 10 is smaller than $numberVariable. In the case below the result would be false.

$numberVariable = 11;
$variableResult = ($numberVariable < 10 ? TRUE : FALSE ); 

A real example on when to use ternary operator in PHP

In the example below you can get the sessions username to see if they are logged in. Using the ternary operator in this way really shows how much cleaner it is and makes the code a lot shorter. If you were using an if else statement you would need to use a lot more space to get the same result.

 
 /**
   * Returns true or false in the user session variable is 
   * @return string 
   */
    public static function getUserSession()
    {
       return (!isset($_SESSION['username']) ? '' : $_SESSION['username']);
    }