Search code examples
phpoperator-keyword

What does double question mark (??) operator mean in PHP


I was diving into Symfony framework (version 4) code and found this piece of code:

$env = $_SERVER['APP_ENV'] ?? 'dev';

I'm not sure what this actually does but I imagine that it expands to something like:

$env = $_SERVER['APP_ENV'] != null ? $_SERVER['APP_ENV'] : 'dev';

Or maybe:

$env = isset($_SERVER['APP_ENV']) ? $_SERVER['APP_ENV'] : 'dev';

Does someone have any precision about the subject?

Note: the main difference between my question and this question is that most of people (like me before) ignore that the double question mark is called null coalescing operator. Thus, this question is more relevant and accessible to beginners.


Solution

  • It's the "null coalescing operator", added in php 7.0. The definition of how it works is:

    It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

    So it's actually just isset() in a handy operator.

    Those two are equivalent1:

    $foo = $bar ?? 'something';
    $foo = isset($bar) ? $bar : 'something';
    

    Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce

    In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

    And original RFC https://wiki.php.net/rfc/isset_ternary


    EDIT: As this answer gets a lot of views, little clarification:

    1There is a difference: In case of ??, the first expression is evaluated only once, as opposed to ? :, where the expression is first evaluated in the condition section, then the second time in the "answer" section.