Search code examples
phpif-statementconditional-statementsoperator-keyword

If statement With One equals sign and Two Question Marks - PHP


Just looking at the index.php page in Symfony 4. Just wondered if someone could clarify what this means?

if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? false) {
    Request::setTrustedHosts([$trustedHosts]);
}

I'm thinking this this equivalent to the following but not sure thanks.

if(isset( $_SERVER['TRUSTED_HOSTS'] )){

   $trustedHosts = $_SERVER['TRUSTED_HOSTS'];
   Request::setTrustedHosts([$trustedHosts]);
  
}

Solution

  • It's equivalent to:

    $trustedHosts = isset($_SERVER['TRUSTED_HOSTS']) ? $trustedHosts : false;
    if ($trustedHosts) {
        Request::setTrustedHosts([$trustedHosts]);
    }
    

    The difference is that your rewrite only sets $trustedHosts when $_SERVER['TRUSTED_HOSTS'] is set. But the actual code sets the variable always, giving it a default value if the $_SERVER element isn't set.