Table Of Contents
Problem
You need to check if a variable exists and is not null, then provide a default value if it doesn't, resulting in verbose isset() or ternary operator code.
Solution
// Old way with isset()
$username = isset($_GET['user']) ? $_GET['user'] : 'guest';
$page = isset($_GET['page']) ? $_GET['page'] : 1;
// New way with null coalescing operator
$username = $_GET['user'] ?? 'guest';
$page = $_GET['page'] ?? 1;
// Chain multiple null coalescing operators
$config = $userConfig ?? $defaultConfig ?? [];
$name = $user->name ?? $profile->display_name ?? 'Anonymous';
// With arrays and object properties
$data = [
'title' => $post['title'] ?? 'Untitled',
'author' => $post['author'] ?? 'Unknown',
'views' => $post['views'] ?? 0
];
// Function parameters with null coalescing
function processOrder($orderId, $options = null) {
$shipping = $options['shipping'] ?? 'standard';
$priority = $options['priority'] ?? false;
$discount = $options['discount'] ?? 0;
return [
'id' => $orderId,
'shipping' => $shipping,
'priority' => $priority,
'discount' => $discount
];
}
// Null coalescing assignment operator (PHP 7.4+)
$cache['user'] ??= expensive_user_lookup($id);
$settings['theme'] ??= 'default';
// Equivalent to:
$cache['user'] = $cache['user'] ?? expensive_user_lookup($id);
// Working with nested arrays
$config = [
'database' => [
'host' => 'localhost'
// 'port' is missing
]
];
$host = $config['database']['host'] ?? 'localhost';
$port = $config['database']['port'] ?? 3306;
$timeout = $config['database']['timeout'] ?? 30;
// API response handling
function handleApiResponse($response) {
return [
'status' => $response['status'] ?? 'error',
'message' => $response['message'] ?? 'Unknown error',
'data' => $response['data'] ?? [],
'timestamp' => $response['timestamp'] ?? time()
];
}
// Environment variables with defaults
$dbHost = $_ENV['DB_HOST'] ?? 'localhost';
$dbPort = $_ENV['DB_PORT'] ?? 3306;
$debug = $_ENV['DEBUG'] ?? false;
// Comparison with other operators
$value = null;
// Null coalescing: only null and undefined trigger default
echo $value ?? 'default'; // 'default'
echo 0 ?? 'default'; // 0
echo '' ?? 'default'; // ''
echo false ?? 'default'; // false
// Ternary: checks truthiness
echo $value ?: 'default'; // 'default'
echo 0 ?: 'default'; // 'default'
echo '' ?: 'default'; // 'default'
echo false ?: 'default'; // 'default'
// Practical example: User preferences
class UserPreferences {
private $preferences = [];
public function get($key, $default = null) {
return $this->preferences[$key] ?? $default;
}
public function set($key, $value) {
$this->preferences[$key] = $value;
}
}
$prefs = new UserPreferences();
$theme = $prefs->get('theme', 'light');
$language = $prefs->get('language', 'en');
$notifications = $prefs->get('notifications', true);
Explanation
The null coalescing operator ??
returns the left operand if it exists and is not null, otherwise returns the right operand. It's safer and cleaner than isset() checks.
Use ??=
for assignment when the variable doesn't exist or is null. This operator only triggers on null/undefined values, unlike ?:
which triggers on any falsy value.
Share this article
Add Comment
No comments yet. Be the first to comment!