What is the meaning of the '?', '()', and ':' symbols in PHP?

后端 未结 4 1118
一整个雨季
一整个雨季 2021-01-14 02:17

I\'ve finally remembered what to ask. I never really got what : and ? do when a variable is being defined like this:

$ip = ($_SERVER[\'HTTP_X_FORWARDED_FOR\'         


        
4条回答
  •  难免孤独
    2021-01-14 03:19

    The ternary form is basically a shortcut for if->then->else

    I generally avoid it because it's not all that readable.

    $ip = ($_SERVER['HTTP_X_FORWARD_FOR']) ? $_SERVER['HTTP_X_FORWARD_FOR'] : $_SERVER['REMOTE_ADDR'];
    

    is logically equivalent to:

    if($_SERVER['HTTP_X_FORWARD_FOR']){
       $ip = $_SERVER['HTTP_X_FORWARD_FOR'];
    }else{
       $ip = $_SERVER['REMOTE_ADDR'];
    }
    

    It should be said that this is EXACTLY what this is most commonly used for: variable initialization. Very common with form data.

提交回复
热议问题