Categories: Development

PHP ternary operator; shorthand conditional statements

The Shorthand ternary operator in PHP is a much more compressed and essentially one line equivalent to the traditional tabbed if-else comparison that can easily span several lines.

The ever common if-else conditional statement looks like this:

if ($var) {
    echo 'Yes';
} else {
    echo 'No';
}

If $var is true then yes will be displayed.

With ternary the statement layout is as follows:

condition ? true : false;

Instead of using five or more lines the comparison is done on just one! The outcome is separated by : with the true outcome being before and false outcome after it.

Here is that first example but in a ternary style:

echo ($var) ? 'Yes' : 'No';

It does exactly the same thing, just saves space.

Another example and a more common usage type being:

echo 'Welcome ' . (isset($_SESSION['uid']) && !empty($_SESSION['uid']) ? $_SESSION['username'] : 'guest') . '';

If the session is set and not empty then “Welcome username” will be outputted else it will say “Welcome guest”.

This is shorter than writing it out traditionally however I don’t see it as easier to read, likely due to them not being used a lot personally.

Going through recent code I can find plenty of times when ternary could have been used like:

public function validateEmail(): bool
{
    if (filter_var($this->email, FILTER_VALIDATE_EMAIL) && strlen($this->email) <= 60) {
        return true;//Valid email address
    } else {
        return false;
    }
}

Turned into:

public function validateEmail(): bool
{
    return (filter_var($this->email, FILTER_VALIDATE_EMAIL) && strlen($this->email) <= 60) ? true : false;
}

Its use comes down to personal preference.

 

Share
Tags: PHPWeb Dev

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago