Using the ternary operator in PHP

The ternary operator is an excellent and often underutilized way to quickly evaluate a variable in place of an if/else statement. The syntax is clean and can greatly simplify code.

( expr1 ) ? ( expr2 ) : ( expr3 )

Take the following code for example where we determine how to greet a user.

<?php
    if(isset($user)) {
        echo $user->name;
    } else {
        echo "Guest";
    }
?>

The code above is simple enough but let’s see how we can improve it by refactoring using a ternary operator.

<?php echo (isset($user)) ? $user->name : "Guest"; ?>

Update 1: There is a great collection of examples over at dzone.

Update 2: Found another nice tips and tricks post over at dzone.

Update 3: One more to check out.

Leave a Reply