Bird
Raised Fist0
PHPprogramming~20 mins

Null safe operator in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Null Safe Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this PHP code using the null safe operator?

Consider the following PHP code snippet. What will it output?

PHP
<?php
class Profile {
    public ?string $email = null;
}
class User {
    public ?Profile $profile = null;
}

$user = new User();
echo $user->profile?->email ?? 'No email';
?>
ANo email
BError: Trying to access property on null
Cnull
DEmpty string
Attempts:
2 left
💡 Hint

The null safe operator returns null if the left side is null, so the null coalescing operator will provide the fallback.

❓ Predict Output
intermediate
2:00remaining
What does this PHP code print when using the null safe operator with nested objects?

Given the code below, what will be printed?

PHP
<?php
class Engine {
    public ?string $type = 'V8';
}
class Car {
    public ?Engine $engine = null;
}

$car = new Car();
echo $car->engine?->type ?? 'No engine';
?>
ANo engine
BV8
Cnull
DError: Undefined property
Attempts:
2 left
💡 Hint

Check if engine is set before accessing type.

❓ Predict Output
advanced
2:00remaining
What is the output of this PHP code using null safe operator with method chaining?

Analyze the code below and select the correct output.

PHP
<?php
class Address {
    public ?string $city = 'Paris';
}
class User {
    public ?Address $address = null;
    public function getAddress(): ?Address {
        return $this->address;
    }
}

$user = new User();
echo $user->getAddress()?->city ?? 'Unknown city';
?>
Anull
BParis
CUnknown city
DFatal error: Call to a member function on null
Attempts:
2 left
💡 Hint

Consider what getAddress() returns and how the null safe operator works with method calls.

❓ Predict Output
advanced
2:00remaining
What is the output of this PHP code using null safe operator on null?

What will this code output?

PHP
<?php
class Book {
    public ?string $title = 'PHP Guide';
}

$book = null;
echo $book?->title;
?>
AFatal error: Call to undefined method string::title()
BNo output, prints nothing
CParse error: syntax error, unexpected '?->'
DFatal error: Call to a member function title() on null
Attempts:
2 left
💡 Hint

The null safe operator short-circuits when the left side is null and does not evaluate the right side.

🧠 Conceptual
expert
3:00remaining
How many items are in the resulting array after this PHP code runs?

Consider this PHP code using null safe operator inside a loop. How many items will the $results array contain?

PHP
<?php
class Item {
    public ?string $name;
    public function __construct(?string $name) {
        $this->name = $name;
    }
}

$items = [new Item('A'), null, new Item(null), new Item('D')];
$results = [];
foreach ($items as $item) {
    $results[] = $item?->name ?? 'Unknown';
}
print_r($results);
?>
A1
B3
C2
D4
Attempts:
2 left
💡 Hint

Count how many times the loop runs and what values are added to $results.

Practice

(1/5)
1. What does the null safe operator ?-> do in PHP?
easy
A. It allows accessing a property or method only if the object is not null, otherwise returns null.
B. It throws an error if the object is null when accessing a property or method.
C. It converts null values to empty strings automatically.
D. It forces the object to be non-null before accessing properties or methods.

Solution

  1. Step 1: Understand the null safe operator purpose

    The null safe operator ?-> is used to safely access properties or methods of an object that might be null.
  2. Step 2: Behavior when object is null

    If the object is null, instead of throwing an error, it returns null immediately without calling the property or method.
  3. Final Answer:

    It allows accessing a property or method only if the object is not null, otherwise returns null. -> Option A
  4. Quick Check:

    Null safe operator = safe access or null return [OK]
Hint: Think: safe access without errors returns null if null [OK]
Common Mistakes:
  • Assuming it throws an error on null
  • Confusing it with the regular object operator ->
  • Thinking it converts null to empty string
2. Which of the following is the correct syntax to use the null safe operator in PHP?
easy
A. $user.?getName();
B. $user->?getName();
C. $user?->getName();
D. $user?getName();

Solution

  1. Step 1: Recall the correct null safe operator syntax

    The null safe operator is written as ?-> immediately after the variable name.
  2. Step 2: Check each option

    $user?->getName(); uses ?-> correctly. Options B, C, and D have incorrect placements or missing characters.
  3. Final Answer:

    $user?->getName(); -> Option C
  4. Quick Check:

    Correct syntax = ?-> [OK]
Hint: Remember: question mark before arrow ?-> is correct [OK]
Common Mistakes:
  • Placing ? after -> or in wrong position
  • Using only ? without ->
  • Confusing with ternary operator syntax
3. What will be the output of the following PHP code?
$user = null;
echo $user?->getName() ?? 'Guest';
medium
A. Empty string
B. Error: Call to a member function getName() on null
C. null
D. Guest

Solution

  1. Step 1: Evaluate the null safe operator usage

    $user is null, so $user?->getName() returns null safely without error.
  2. Step 2: Apply null coalescing operator

    The expression uses ?? 'Guest', so since left side is null, it returns 'Guest'.
  3. Final Answer:

    Guest -> Option D
  4. Quick Check:

    Null safe + null coalescing = fallback value [OK]
Hint: Null safe returns null, ?? provides fallback [OK]
Common Mistakes:
  • Expecting an error when calling method on null
  • Confusing null safe with regular -> operator
  • Ignoring the null coalescing fallback
4. Identify the error in the following PHP code using the null safe operator:
$order = null;
echo $order?->getItem()->getName();
medium
A. No error, code runs fine and outputs null.
B. Error because getItem() is called on null without null safe operator.
C. Syntax error due to missing semicolon.
D. Error because null safe operator cannot be chained.

Solution

  1. Step 1: Analyze the null safe operator chaining

    The first null safe operator ?-> safely calls getItem() on $order which is null, so it returns null.
  2. Step 2: Check the next method call

    Then getName() is called on the result of getItem() without null safe operator, causing an error because it's called on null.
  3. Final Answer:

    Error because getItem() is called on null without null safe operator. -> Option B
  4. Quick Check:

    Chained calls need ?-> on each nullable step [OK]
Hint: Use ?-> before every nullable method call in chain [OK]
Common Mistakes:
  • Assuming one ?-> covers all chained calls
  • Ignoring that getName() is called on null
  • Thinking null safe operator fixes all errors automatically
5. Given the following PHP code, what will be the output?
class Profile {
    public ?string $nickname = null;
}

class User {
    public ?Profile $profile = null;
}

$user = new User();
$user->profile = new Profile();
$user->profile->nickname = null;

echo $user?->profile?->nickname ?? 'No nickname';
hard
A. No nickname
B. null
C. Error: Cannot access property on null
D. Empty string

Solution

  1. Step 1: Trace object properties and null safe operator

    $user is an object, $user->profile is an object, but $user->profile->nickname is null.
  2. Step 2: Evaluate null safe operator and null coalescing

    The expression $user?->profile?->nickname safely returns null because nickname is null. Then ?? 'No nickname' returns 'No nickname'.
  3. Final Answer:

    No nickname -> Option A
  4. Quick Check:

    Null safe returns null, ?? fallback used [OK]
Hint: Null safe returns null, ?? gives fallback string [OK]
Common Mistakes:
  • Expecting null output instead of fallback string
  • Thinking null safe operator throws error on null property
  • Confusing null and empty string values
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