How do I use the ternary operator ( ? : ) in PHP as a shorthand for “if / else”?

后端 未结 14 1119
我在风中等你
我在风中等你 2020-11-22 08:34

Based on the examples from this page, I have the working and non-working code samples below.

Working code using if statement:

if (!empty         


        
相关标签:
14条回答
  • 2020-11-22 09:02

    Basic True / False Declaration

    $is_admin = ($user['permissions'] == 'admin' ? true : false);
    

    Conditional Welcome Message

    echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';
    

    Conditional Items Message

    echo 'Your cart contains '.$num_items.' item'.($num_items != 1 ? 's' : '').'.';
    

    ref: https://davidwalsh.name/php-ternary-examples

    0 讨论(0)
  • 2020-11-22 09:05

    Note that when using nested conditional operators, you may want to use parenthesis to avoid possible issues!

    It looks like PHP doesn't work the same way as at least Javascript or C#.

    $score = 15;
    $age = 5;
    
    // The following will return "Exceptional"
    echo 'Your score is: ' . ($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average'));
    
    // The following will return "Horrible"
    echo 'Your score is: ' . ($score > 10 ? $age > 10 ? 'Average' : 'Exceptional' : $age > 10 ? 'Horrible' : 'Average');
    

    The same code in Javascript and C# return "Exceptional" in both cases.

    In the 2nd case, what PHP does is (or at least that's what I understand):

    1. is $score > 10? yes
    2. is $age > 10? no, so the current $age > 10 ? 'Average' : 'Exceptional' returns 'Exceptional'
    3. then, instead of just stopping the whole statement and returning 'Exceptional', it continues evaluating the next statement
    4. the next statement becomes 'Exceptional' ? 'Horrible' : 'Average' which returns 'Horrible', as 'Exceptional' is truthy

    From the documentation: http://php.net/manual/en/language.operators.comparison.php

    It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious.

    0 讨论(0)
  • 2020-11-22 09:07

    It's the Ternary operator a.k.a Elvis operator (google it :P) you are looking for.

    echo $address['street2'] ?: 'Empty'; 
    

    It returns the value of the variable or default if the variable is empty.

    0 讨论(0)
  • 2020-11-22 09:14

    The ternary operator is just a shorthand for and if/else block. Your working code does not have an else condition, so is not suitable for this.

    The following example will work:

    echo empty($address['street2']) ? 'empty' : 'not empty';
    
    0 讨论(0)
  • 2020-11-22 09:14

    I think you used the brackets the wrong way. Try this:

    $test = (empty($address['street2']) ? 'Yes <br />' : 'No <br />');
    

    I think it should work, you can also use:

    echo (empty($address['street2']) ? 'Yes <br />' : 'No <br />');
    
    0 讨论(0)
  • 2020-11-22 09:14

    I think you probably should not use ternary operator in php. Consider next example:

    <?php
    
    function f1($n) {
        var_dump("first funct");
        return $n == 1;
    }
    
    function f2($n) {
        var_dump("second funct");
        return $n == 2;
    }
    
    
    $foo = 1;
    $a = (f1($foo)) ? "uno" : (f2($foo)) ? "dos" : "tres";
    print($a);
    

    How do you think, what $a variable will contain? (hint: dos) And it will remain the same even if $foo variable will be assigned to 2.

    To make things better you should either refuse to using this operator or surround right part with braces in the following way:

    $a = (f1($foo)) ? "uno" : ((f2($foo)) ? "dos" : "tres");
    
    0 讨论(0)
提交回复
热议问题