In PHP the ternary operator can really help clean up your code, especially for short conditional assignments. The ternary operator can help improve the readability of your code as well. Someone recently enlightened me and showed me the Elvis operator and it’s usage for simple assignments. Using the Elvis operator can help reduce redundancy of your conditions and shorten the length of your assignments. How many of us have seen something like the this?

The Elvis operator can be used to clean this up so it looks like this:

That’s much cleaner and can make the code a little more readable. The Elvis operator has been available since PHP 5.3 so check your version before using on your site. According to php.net, “Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.” Enjoy!

4 comments on “PHP and the Elvis Operator

  1. Paul D says:

    That is brilliant. Looking forward to trying that out.

  2. Marek Snopkowski says:

    Ternary operator with empty second value is indeed useful, but not in that case. Sole purpose of using:

    $varOne = isset($_GET[‘var_one’]) ? $_GET[‘var_one’] : null;

    is to simply avoid PHP Notice listing.
    However if we exclude E_NOTICE from error_reporting() on we can as well type:

    $varOne = $_GET[‘var_one’];

    as undefined variable/index will evaluate to null value.

    Changing however example to this:

    // before 5.3
    $limit= isset($_GET[‘limit’]) ? $_GET[‘limit’] : 10;

    // since 5.3
    $limit = $_GET[‘limit’] ? : 10;

    with a note that it can trigger E_NOTICE would make more sense.

    Keep up the good work. Thanks.

  3. Benjamin Noone says:

    There is one downside to the method proposed.
    Supposing $b has not been set when the following code is run:
    $a = $b ?: $c;
    The result of $a will be whatever $c contianed as wished, however an error is thrown because $b has not been instantiated.
    To solve this problem one easy fix would be to use the “error control operator” @ like so:
    $a = @$b ?: $c;
    and it will catch your undefined index error.

  4. austinamerican statesman com says:

    Prior to PHP 7, callbacks that needed to be executed per regular expression required the callback function to be polluted with lots of branching.

Comments are closed.