1// The null coalescing operator (??) is used to replace the ternary operation
2// in conjunction with isset() function and returns its first operand if it
3// exists and is NOT NULL; otherwise it returns its second operand.
4$username = $_GET['username'] ?? 'not passed';
5
6// Equivalent code using ternary operator
7$username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
1// if $_POST['name'] doesn't exist $result will equal to John
2$result = $_POST['name'] ?? 'John';
1
2<?php
3// Fetches the value of $_GET['user'] and returns 'nobody'
4// if it does not exist.
5$username = $_GET['user'] ?? 'nobody';
6// This is equivalent to:
7$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
8
9// Coalescing can be chained: this will return the first
10// defined value out of $_GET['user'], $_POST['user'], and
11// 'nobody'.
12$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
13?>
14
15