Search code examples
phpternary-operator

Ternary operators and variable reassignment in PHP


I've perused the questions on ternary operators vs. if/else structures, and while I understand that under normal circumstances there is no performance loss/gain in using ternary operators over if/else structures, I've not seen any mention of this situation. Language specific to PHP (but any language agnostic details are welcome) does the interpreter reassign values in situations like this:

$foo = 'bar'
$foo = strlen($foo) > 3 ? substr($foo, 0, 3) : $foo;

Since this would evaluate to $foo = $foo; is this inefficient, or does the interpreter simply overlook/discard this evaluation?

On a side note, what about:

!defined('SECURE') ? exit : null;

Solution

  • I don't know if your first example is inefficient, but it sure is pointless. I still think an if statement is clearer:

    $foo = 'bar';
    
    if (strlen($foo) > 3)
        $foo = substr($foo, 0, 3);
    

    And while the following works, it makes no sense to place null at the end because a ternary operator is meant to be used to evaluate expressions/values, but here null does nothing other than to prevent a parse error:

    !defined('SECURE') ? exit : null;
    

    More commonly, you would see this, an example of boolean short-circuiting (or exit doesn't execute if SECURE is not defined, because the or conditional expression evaluates to true automatically once at least one condition is found to be true):

    defined('SECURE') or exit;
    

    The point I'm trying to make is this: don't use ternary conditional expressions just because you can.