The ??
operator in PHP is called the Null Coalescing Operator
. It provides a simple way to handle null
or undefined values, helping to prevent errors and making your code cleaner.
🛠 Syntax of the Null Coalescing Operator
The operator checks if a variable is set and not null
. If it’s null
, it returns a default value.
$variable = $_GET['name'] ?? 'Guest';
This means: “If $_GET['name']
is set, use it; otherwise, use 'Guest'
.”
📝 Example 1: Handling Undefined Variables
Let’s safely access a variable that may not be set.
<?php $name = $_GET['name'] ?? 'Guest'; echo "Hello, " . $name; ?>
📝 Example 2: Using Multiple Null Coalescing Operators
You can chain multiple values to find the first non-null
value.
<?php $username = $_POST['username'] ?? $_GET['username'] ?? 'Anonymous'; echo "User: " . $username; ?>
📝 Example 3: Using Null Coalescing in Arrays
Check if an array key exists before using it.
<?php $data = ['name' => 'Alice']; $user = $data['name'] ?? 'Unknown'; echo $user; // Output: Alice ?>
🎯 Why Use the Null Coalescing Operator?
- ✅ Prevents
undefined variable
errors - ✅ Makes code cleaner and shorter
- ✅ Great for handling form inputs and GET/POST requests
📝 Practice Time!
Try modifying the examples above and see how the null coalescing operator works with different values. The best way to learn is by experimenting! 🚀