What is this alternative if/else syntax in PHP called?

前端 未结 2 1650
一向
一向 2020-12-31 17:29

What is the name of the following type of if/else syntax:

print $foo = ($hour < 12) ? \"Good morning!\" : \"Good afternoon!\";

I couldn\

相关标签:
2条回答
  • 2020-12-31 18:24

    It's called the ternary operator - although many people call it the "?: operator" because "ternary" is such a seldom-used word.

    0 讨论(0)
  • 2020-12-31 18:32

    This is called a ternary expression

    http://php.net/manual/en/language.expressions.php

    You should note, this is not an "alternate syntax for if" as it should not be used to control the flow of a program.

    In the simple example of setting variables, it can help you avoid lengthy if statements like this: (ref: php docs)

    // Example usage for: Ternary Operator
    $action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
    
    // The above is identical to this if/else statement
    if (empty($_POST['action'])) {
        $action = 'default';
    } else {
        $action = $_POST['action'];
    }
    

    However it can be used other places than just simple variable assignent

    function say($a, $b) {
        echo "{$a} {$b}";
    }
    
    $foo = false;
    
    say('hello', $foo ? 'world' : 'planet');
    
    //=> hello planet
    
    0 讨论(0)
提交回复
热议问题