0
0
PHPprogramming~15 mins

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

Choose your learning style9 modes available
Using the Null Coalescing Operator in PHP
📖 Scenario: Imagine you are building a simple PHP script that reads user input from an array. Sometimes the input might be missing, and you want to provide a default value instead of causing an error.
🎯 Goal: You will create a PHP script that uses the null coalescing operator ?? to safely access array values and provide default values when keys are missing.
📋 What You'll Learn
Create an associative array called userInput with specific keys and values
Create a variable called defaultName with a default string value
Use the null coalescing operator ?? to assign a variable name from userInput or defaultName
Print the value of name to display the result
💡 Why This Matters
🌍 Real World
Web developers often need to handle missing data safely when reading user input or configuration settings. The null coalescing operator helps avoid errors and provides default values easily.
💼 Career
Understanding how to use the null coalescing operator is important for writing clean, error-free PHP code in web development jobs.
Progress0 / 4 steps
1
Create the user input array
Create an associative array called userInput with these exact entries: 'name' => 'Alice', 'age' => 30.
PHP
Need a hint?

Use square brackets [] to create the array and separate key-value pairs with commas.

2
Set a default name
Create a variable called defaultName and set it to the string 'Guest'.
PHP
Need a hint?

Use the assignment operator = to set the string value.

3
Use the null coalescing operator
Create a variable called name and assign it the value of $userInput['name'] ?? $defaultName using the null coalescing operator ??.
PHP
Need a hint?

The null coalescing operator ?? returns the left value if it exists and is not null; otherwise, it returns the right value.

4
Print the result
Write a print statement to display the value of the variable name.
PHP
Need a hint?

Use print($name); to show the value on the screen.