equal operator php code example

Example 1: php ?? vs ?:

<?php
var_dump(null ?? '`null` is null'); // `null` is null
var_dump(null ?: '`null` is empty'); // null
var_dump(true ?? '`true` is null'); // true
var_dump(true ?: '`true` is empty'); // true
var_dump(false ?? '`false` is null'); // false
var_dump(false ?: '`false` is empty'); // `false` is empty"
var_dump('' ?? 'empty string is null'); // ""
var_dump('' ?: 'empty string is empty'); // "empty string is empty"
var_dump(empty(null) ?: '`null` is not empty'); // true

Example 2: php ?:

// Example usage for: Ternary Operator
$action = $_POST['action'] ?: 'default';

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

Tags:

Php Example