PHP7 ?? and ?: the role and difference

Posted Jun 29, 20201 min read

We often have to write code similar to this judgment

//determine if there is a variable
$a = isset($b)?$b:$c;

//Determine if the variable is empty
$a = !empty($b)?$b:$c;

PHP7 has new syntactic sugar, simplified(PHP version must be greater than 7)

//determine if there is a variable
$a = $b??$c; //Equivalent to $a = isset($b)?$b:$c;

//Determine if the variable is empty
$a = $b?:$c; //Equivalent to $a = !empty($b)?$b:$c;

The difference is

  • ?? Only judge whether the variable exists

  • ?:you also need to determine whether the variable is empty

    $a = [];
    print_r($a ??'Go this way');
    //[]
    print_r($a ?:'Go this way');
    //'Go this way'