PHP Null Coalescing Nesting AND Chaining

 ← Dev Articles
👍 0
👎 0

PHP Null Coalescing Nesting AND Chaining

The null coalescing operator is essential for writing clean, safe PHP code that gracefully handles missing data without generating warnings or errors.

 

Null Coalescing Assignment Operator (??)

 

 // ternary operator usage

 $value = isset($a) ? $a : (isset($b) ? $b : $c);

 

 // null-coalescing shorthand for above solution

 $value = $a ?? $b ?? $c;



Null Coalescing Assignment Operator (??=)

 

 // Only assign if variable is null or doesn't exist

 $array['key'] ??= 'default value';

 $user->name ??= 'Anonymous';

 

 // Equivalent to:

 if (!isset($array['key'])) {

    $array['key'] = 'default value';

 }

 

 

Use with error suppression

 

 $value = $object->property->nestedProperty ?: 'default';

 echo "Value: ".$value."\r\n"; //Warning is thrown

 

 

 $value = @$object->property->nestedProperty ?? 'default';

 echo "Value: ".$value."\r\n"; // Value: default