PinoyTech.org

CodeIgniter, Kohana, Mootools, jQuery and CSS

PHP's Ternary Operator

Posted by teejay on November 7, 2009

This is probably something old for most PHP developers out there. Unfortunately, I see tons of questions about what the ternary operator.

Ternary Operator

$time = empty($pail) ? 'time to fetch water' : 'time for a bath';

The above effectively, translates into the following:

if (empty($pail))
{
    $time = 'time to fetch water';
}
else
{
    $time = 'time for a bath';
}

PHP5.3 introduces the ability to omit the middle part like so:

$menthol_candy =  $clorets ? : FALSE;

If the expression evaluates to TRUE, the boolean TRUE will be passed the $mentol_candy

Categories: Web Development

Tags: php

2 Comments

Mitch

I don’t like the ternary operator. It kind of clutter my code. I still like the old if statement.

November 8th 2009

Thorpe Obazee

@Mitch. You can always format your code like this.

$time = empty($pail)
        ? 'time to fetch water'
        : 'time for a bath';

This makes it much neater.

November 8th 2009

Comments are not allowed