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

后端 未结 4 1120
一整个雨季
一整个雨季 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:18

    It's known as a ternary operator and is shorthand for (in your case):

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

提交回复
热议问题