What are the PHP operators “?” and “:” called and what do they do?

前端 未结 10 1565

What are the ? and : operators in PHP?

For example:

(($request_type == \'SSL\') ? HTTPS_SERVER : HTTP_SERVER)
10条回答
  •  醉话见心
    2020-11-22 05:06

    Conditional operator ? : is an operator which is used to check a condition and select a value depending on the value of the condition. It is expressed in the following form:

    variable = condition ? expression1 : expression2;
    

    It works as follows...

    1. Firstly, condition is evaluated.
    2. If the condition is true, then expression1 is evalauated. And the value of expression1 is assigned to the variable.
    3. If the condition is false, then expression2 is evaluated. And the value of expression2 is assigned to the variable.

    For example:

    x = (a>b) ? 5 : 9
    

    In this, for x, firstly the condition (a>b) is evaluated. If this condition becomes true, then x will become the value 5 (ie, x=5). But if the condition (a>b) becomes false, then x will attain the value 9 (ie, x=9).

    Ternary Operator

    Sometimes conditional operator ? : is also called a ternary operator. This is so because it involves three operands. For example:

    x ? y : z
    

    Here, x,y and z are the three operands. If condition x is true, then value y is assigned otherwise value z is assigned.

提交回复
热议问题