Bird
Raised Fist0
PHPprogramming~10 mins

Null coalescing in conditions in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Null coalescing in conditions
Start
↓
Check if variable is set and not null
↓
Use variable
↓
Continue with chosen value
↓
End
The program checks if a variable exists and is not null; if yes, it uses that variable, otherwise it uses a default value.
Execution Sample
PHP
<?php
$value = $input ?? 'default';
if ($value) {
    echo "Value is: $value";
} else {
    echo "No value";
}
?>
This code uses null coalescing to assign $value and then checks if $value is truthy to print a message.
Execution Table
StepVariable $inputExpression $input ?? 'default'Condition if($value)Branch TakenOutput
1null'default'if('default')True branchValue is: default
2'Hello''Hello'if('Hello')True branchValue is: Hello
3'' (empty string)''if('')False branchNo value
400if(0)False branchNo value
5falsefalseif(false)False branchNo value
6unset (undefined)'default'if('default')True branchValue is: default
💡 Execution stops after printing output for each test case.
Variable Tracker
VariableStartTest 1Test 2Test 3Test 4Test 5Test 6
$inputundefinednull'Hello'''0falseundefined
$valueundefined'default''Hello'''0false'default'
Key Moments - 3 Insights
Why does the condition fail when $value is an empty string or 0?
Because in PHP, empty string and 0 are considered false in conditions, so the else branch runs as shown in rows 3 and 4 of the execution_table.
What happens if $input is not set at all?
The null coalescing operator uses the default value, so $value becomes 'default' and the if condition is true, as shown in row 6.
Does null coalescing check only for null or also for undefined variables?
It checks both: if the variable is not set or is null, it uses the default value, demonstrated in rows 1 and 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of $value at Step 2 when $input is 'Hello'?
A'default'
B'Hello'
Cnull
D'' (empty string)
💡 Hint
Check the 'Expression $input ?? 'default'' column at Step 2 in the execution_table.
At which step does the condition if($value) evaluate to false because $value is 0?
AStep 3
BStep 5
CStep 4
DStep 6
💡 Hint
Look at the 'Condition if($value)' column and find where the value is 0.
If $input was set to false, what output would the program produce according to the execution_table?
ANo value
BValue is: false
CValue is: default
DError
💡 Hint
Check Step 5 output in the execution_table where $input is false.
Concept Snapshot
Null coalescing operator (??) returns the left value if set and not null; otherwise, it returns the right value.
Used in conditions to provide defaults.
Example: $value = $input ?? 'default';
If $input is null or unset, $value is 'default'.
Conditions treat '', 0, false as false even if not null.
Full Transcript
This visual execution shows how PHP's null coalescing operator works in conditions. It checks if a variable is set and not null; if yes, it uses that variable; otherwise, it uses a default value. The execution table traces different values of the input variable and how the condition if($value) behaves. For example, when input is null or unset, the default is used. When input is an empty string or zero, the condition evaluates to false because PHP treats these as false in conditions. The variable tracker shows how $input and $value change in each test. Key moments clarify common confusions about falsey values and unset variables. The quiz tests understanding of these behaviors by referencing the execution table and variable tracker.

Practice

(1/5)
1. What does the null coalescing operator ?? do in PHP conditions?
easy
A. Always returns the second operand regardless of the first.
B. Returns the first operand if it exists and is not null; otherwise returns the second operand.
C. Checks if both operands are null and returns true if so.
D. Throws an error if the first operand is null.

Solution

  1. Step 1: Understand the operator's purpose

    The null coalescing operator ?? checks if the left value exists and is not null.
  2. Step 2: Determine the return value

    If the left value is null or missing, it returns the right value as a fallback.
  3. Final Answer:

    Returns the first operand if it exists and is not null; otherwise returns the second operand. -> Option B
  4. Quick Check:

    Null coalescing = first non-null value [OK]
Hint: Think: "Use first value if valid, else fallback" [OK]
Common Mistakes:
  • Confusing it with logical OR operator
  • Assuming it throws errors on null
  • Believing it always returns second operand
2. Which of the following is the correct syntax to use null coalescing in a PHP if condition?
easy
A. if ($value || 'default') { ... }
B. if ($value ?: 'default') { ... }
C. if ($value ?? 'default') { ... }
D. if ($value ??= 'default') { ... }

Solution

  1. Step 1: Identify null coalescing syntax

    The null coalescing operator is ?? and used like $value ?? 'default'.
  2. Step 2: Check each option

    if ($value ?? 'default') { ... } uses ?? correctly inside the if condition. if ($value ?: 'default') { ... } uses the ternary shortcut, not null coalescing. if ($value || 'default') { ... } uses logical OR, which is different. if ($value ??= 'default') { ... } uses ??= which is an assignment operator, not a condition.
  3. Final Answer:

    if ($value ?? 'default') { ... } -> Option C
  4. Quick Check:

    Correct null coalescing syntax = if ($value ?? 'default') { ... } [OK]
Hint: Look for ?? operator inside the if condition [OK]
Common Mistakes:
  • Mixing null coalescing with ternary or OR operators
  • Using assignment operator ??= inside if
  • Missing parentheses or wrong operator
3. What will be the output of this PHP code?
$name = null;
$display = $name ?? 'Guest';
echo $display;
medium
A. Guest
B. Empty string
C. Error
D. null

Solution

  1. Step 1: Evaluate the variable $name

    The variable $name is set to null.
  2. Step 2: Apply null coalescing operator

    The expression $name ?? 'Guest' returns 'Guest' because $name is null.
  3. Final Answer:

    Guest -> Option A
  4. Quick Check:

    null ?? 'Guest' = 'Guest' [OK]
Hint: Null on left means right value is chosen [OK]
Common Mistakes:
  • Thinking null prints as 'null' string
  • Confusing null coalescing with OR operator
  • Expecting error when variable is null
4. Find the error in this PHP code snippet using null coalescing:
if ($user ?? 'guest') {
echo 'Welcome!';
}
medium
A. The condition always evaluates to true, so it may not work as intended.
B. The variable $user must be checked with isset() before using ??.
C. The null coalescing operator cannot be used inside if conditions.
D. The operator ?? should be replaced with logical OR ||.

Solution

  1. Step 1: Understand the condition logic

    The expression $user ?? 'guest' returns $user if set and not null, else 'guest'.
  2. Step 2: Analyze boolean evaluation

    Since 'guest' is a non-empty string, the condition is always true, even if $user is null or false.
  3. Final Answer:

    The condition always evaluates to true, so it may not work as intended. -> Option A
  4. Quick Check:

    Non-null fallback makes condition always true [OK]
Hint: Check if fallback value makes condition always true [OK]
Common Mistakes:
  • Assuming null coalescing checks boolean truth
  • Thinking isset() is required with ?? operator
  • Replacing ?? with || without reason
5. You want to display a username if it exists and is not null, otherwise show 'Anonymous'. Which code correctly uses null coalescing in a condition to echo the username or fallback?
hard
A. echo $username || 'Anonymous';
B. echo isset($username) ? $username : 'Anonymous';
C. echo $username ?: 'Anonymous';
D. echo $username ?? 'Anonymous';

Solution

  1. Step 1: Understand the requirement

    We want to print $username if it exists and is not null; otherwise print 'Anonymous'.
  2. Step 2: Compare options

    echo isset($username) ? $username : 'Anonymous'; uses ternary with isset(), which works but is longer. echo $username ?? 'Anonymous'; uses null coalescing ?? which directly checks for null and provides fallback. echo $username ?: 'Anonymous'; uses the ternary shortcut ?: which treats empty strings or 0 as false, not just null. echo $username || 'Anonymous'; uses logical OR which is incorrect syntax for echo.
  3. Final Answer:

    echo $username ?? 'Anonymous'; -> Option D
  4. Quick Check:

    Null coalescing for fallback = echo $username ?? 'Anonymous'; [OK]
Hint: Use ?? to fallback only on null, not falsy values [OK]
Common Mistakes:
  • Using ?: which treats empty strings as false
  • Using logical OR which is invalid here
  • Overcomplicating with isset() ternary
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard