0
0
PHPprogramming~15 mins

Null coalescing in conditions in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Null coalescing in conditions
📖 Scenario: You are building a simple PHP script to check user input from a form. Sometimes the input might be missing or empty. You want to use the null coalescing operator to provide a default value when the input is not set.
🎯 Goal: Create a PHP script that uses the null coalescing operator ?? in a condition to check if a user input variable is set. If it is not set, use a default value. Then print a message based on the value.
📋 What You'll Learn
Create a variable $input with a specific value
Create a variable $default with a default string
Use the null coalescing operator ?? in an if condition to check $input or use $default
Print the message showing which value was used
💡 Why This Matters
🌍 Real World
Web forms often have optional fields. Using null coalescing helps handle missing inputs gracefully.
💼 Career
PHP developers use null coalescing to write cleaner, safer code when dealing with user input or data that might be missing.
Progress0 / 4 steps
1
Create the user input variable
Create a variable called $input and set it to null.
PHP
Need a hint?

Use $input = null; to create the variable.

2
Create the default value variable
Create a variable called $default and set it to the string 'Guest'.
PHP
Need a hint?

Use $default = 'Guest'; to create the variable.

3
Use null coalescing in an if condition
Write an if statement that uses the null coalescing operator ?? to check if $input is set; if not, use $default. Inside the if, check if the result equals 'Guest'.
PHP
Need a hint?

Use if (($input ?? $default) === 'Guest') to check the value.

4
Print the result message
Inside the if block, print "Hello, Guest!". Otherwise, print "Hello, " followed by the value of $input.
PHP
Need a hint?

Use print("Hello, Guest!"); inside the if and print("Hello, $input"); inside the else.