Null Coalescing Operator
Part of the Fundamentals section of Coddy's PHP journey — lesson 31 of 71.
The null coalescing operator (??) provides a convenient way to use a default value when a variable is null or doesn't exist. This is especially useful when working with data that might be missing.
The syntax places ?? between the variable to check and the fallback value:
<?php
$username = null;
$displayName = $username ?? "Guest";
echo $displayName; // Guest
?>PHP checks if $username is null. Since it is, the operator returns "Guest" instead. If $username had a value, that value would be used.
<?php
$username = "Alice";
$displayName = $username ?? "Guest";
echo $displayName; // Alice
?>The null coalescing operator also works when a variable hasn't been defined at all, without triggering an error:
<?php
// $color is not defined anywhere
$selectedColor = $color ?? "blue";
echo $selectedColor; // blue
?>This makes ?? cleaner than using a ternary operator with isset() checks. It's perfect for providing sensible defaults when data might be missing.
Challenge
EasyRead two values from input: a string nickname and a string theme.
Use the null coalescing operator to handle potentially missing values:
- Create a variable
$userNicknamethat is set tonull. Then use the null coalescing operator to assign$displayNicknamethe value of$userNicknameif it exists and is not null, otherwise use thenicknameinput value. - Create a variable
$userThemeand assign it thethemeinput value. Use the null coalescing operator to assign$selectedThemethe value of$userThemeif it exists and is not null, otherwise usedarkas the default. - Use the null coalescing operator directly with an undefined variable
$language(do not define it) to assign$displayLanguagethe value of$languageif it exists, otherwise useEnglishas the default.
Print each result on a new line in this order: $displayNickname, $selectedTheme, $displayLanguage.
Example:
If the inputs are Player1 and light, the output should be:
Player1
light
EnglishIf the inputs are GuestUser and blue, the output should be:
GuestUser
blue
EnglishCheat sheet
The null coalescing operator (??) provides a default value when a variable is null or doesn't exist.
Syntax:
$result = $variable ?? "default value";If $variable is null, the default value is used:
$username = null;
$displayName = $username ?? "Guest";
echo $displayName; // GuestIf $variable has a value, that value is used:
$username = "Alice";
$displayName = $username ?? "Guest";
echo $displayName; // AliceThe operator also works with undefined variables without triggering an error:
// $color is not defined
$selectedColor = $color ?? "blue";
echo $selectedColor; // blueTry it yourself
<?php
// Read input
$nickname = trim(fgets(STDIN));
$theme = trim(fgets(STDIN));
// TODO: Write your code below
// 1. Create $userNickname set to null, then use ?? to assign $displayNickname
// 2. Create $userTheme with the theme input, then use ?? to assign $selectedTheme (default: 'dark')
// 3. Use ?? with undefined $language to assign $displayLanguage (default: 'English')
// Output the results (each on a new line)
echo $displayNickname . "\n";
echo $selectedTheme . "\n";
echo $displayLanguage . "\n";
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators