the code “ : ” in php

前端 未结 7 727
难免孤独
难免孤独 2020-12-22 13:40

I\'m curious to know what the syntax \" : \" mean in php I\'ve seen it a couple of times but I can\'t seem to explain it to myself. Can you also use it in a sentence....or i

相关标签:
7条回答
  • 2020-12-22 13:46

    Perhaps you are referring to the ternary operator, which uses a ? and : as follows:

    $variable = boolean_expression ? "true_value" : "false_value";
    

    This code is shorthand for an if-else:

    if (boolean_expression) {
       $variable = "true_value";
    }
    else {
       $variable = "false_value";
    }
    
    0 讨论(0)
  • 2020-12-22 13:53

    This is a short-form conditional expression, known in PHP as the "ternary operator." See the PHP manual for more details on its usage.

    echo ($sheLovesMe ? "She loves me!" : "She loves me not!");
    
    0 讨论(0)
  • 2020-12-22 13:55

    The ?: operator is a ternary operator called the conditional operator.

    It is conditional because the expressions expr2 and expr3 in expr1 ? expr2 : expr3 are evaluated based on the evaluated return value of expr1:

    • If expr1 evaluates to true, expr2 is evaluated and the return value of expr2 is the return value of the whole ?: operator expression;
    • otherwise expr3 is evaluated and the return value of the ?: operator expression is the return value of expr3.

    Here’s an example:

    echo 1 == 1 ? "true" : "false";
    

    If 1 == 1 evaluates to true, "true" will be echoed, otherwise "false".

    Note that the ?: operator is just a and not the ternary operator. The word ternary just means that there are three operands (op1 ? op2 : op3) just like a binary operator has two operands (e.g. op1 + op2, op1 / op2, op1 % op2, etc.) and unary operators just have one operand (e.g. !op, -op, ~op, etc.).

    0 讨论(0)
  • 2020-12-22 13:59

    How about the shorthand syntax for blocks in PHP embedded in HTML? For example

    <body>
       <h1>Some Header</h1>
       <?php if($somevariable == '4') : ?>
          <h2>Some other thing</h2>
          <p>Some text</p>
       <?php else: ?>
          <h3>Else!</h3>
       <?php endif; ?>
    </body>
    

    Probably doesn't necessarily count as an operator. More of a delimiter here.

    0 讨论(0)
  • Are you talking about the conditional operator?

    
    $a = $gork === 1 ? $foo : $bar;
    
    

    Check out the "Ternary Operator" section on this page: http://php.net/manual/en/language.operators.comparison.php

    It's basically a short cut for an if else, the above code is the same as:

    
    if($gork === 1)
        $a = $foo;
    else
        $a = $bar;
    
    
    0 讨论(0)
  • 2020-12-22 14:10

    It can also refer to a goto

    MyGoto:
        if (DoSomething())
            goto MyGoto;
    

    Very few circumstances warrant a goto, but that's what it can mean if not a ternary operator.

    0 讨论(0)
提交回复
热议问题