Use PHP's Null Coalescing Assignment Operator (??=)

Use PHP's Null Coalescing Assignment Operator (??=)

PHP 7.4 introduced the null coalescing assignment operator (??=). It's a shorthand way to assign a value to a variable if it's null.

$config = [
    'debug' => true,
];

// Old way
if (!isset($config['environment'])) {
    $config['environment'] = 'production';
}

// New way with ??=
$config['environment'] ??= 'production';

var_dump($config);
// Outputs: ['debug' => true, 'environment' => 'production']

This operator simplifies code and makes it more readable, especially when dealing with configuration arrays or setting default values.

← Back to Tips List