Search code examples
phpoperatorsphp-7

Is this '??' is a operator in php or what it's called? Also is it used for empty() or isset() check?


$name = $username ?? '';

I don't know actually what is this ?? called?


Solution

  • ?? is Null coalescing Let suppose

    $x = expr1 ?? expr2
    

    Returns the value of $x.The value of $x is expr1 if expr1 exists, and is not NULL. If expr1 does not exist, or is NULL, the value of $x is expr2.Null coalescing Introduced in PHP 7.

    Other Examples

    <?php
       // variable $user is the value of $_GET['user']
       // and 'anonymous' if it does not exist
       echo $user = $_GET["user"] ?? "anonymous";
       echo("<br>");
      
       // variable $color is "red" if $color does not exist or is null
       echo $color = $color ?? "red";
    ?>