0
0
PHPprogramming~5 mins

Null coalescing in conditions in PHP

Choose your learning style9 modes available
Introduction

Null coalescing helps you pick a value that exists or use a default if it doesn't. It makes checking for missing data easy and clean.

When you want to use a variable if it has a value, or a default if it is missing or null.
When reading user input that might not be set, like form fields.
When working with arrays or objects where some keys or properties might not exist.
When you want to avoid long if-else checks for null or missing values.
Syntax
PHP
$value = $variable ?? $default;

The ?? operator checks if the left side is set and not null.

If the left side is null or not set, it returns the right side value.

Examples
This prints the 'name' from the URL if it exists, otherwise it prints 'Guest'.
PHP
$name = $_GET['name'] ?? 'Guest';
echo $name;
This uses the user's age if set, or 18 as a default.
PHP
$age = $user['age'] ?? 18;
echo $age;
This checks if 'color' exists and is not null, then prints a message accordingly.
PHP
$color = $settings['color'] ?? null;
if ($color) {
    echo "Color is set.";
} else {
    echo "No color.";
}
Sample Program

This program sets $userInput to null, so it uses $defaultInput. It then prints the chosen input.

PHP
<?php
// Example of null coalescing in a condition
$userInput = null;
$defaultInput = 'default value';

// Use null coalescing to pick user input or default
$input = $userInput ?? $defaultInput;

if ($input) {
    echo "Input is: $input";
} else {
    echo "No input provided.";
}
OutputSuccess
Important Notes

Null coalescing only checks for null or unset, not for empty strings or zero.

You can chain multiple null coalescing operators like $a ?? $b ?? $c.

Summary

Null coalescing helps pick the first value that exists and is not null.

It makes your code shorter and easier to read when checking for missing values.

Use it in conditions to provide defaults or fallback values smoothly.