Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

PHP 7 Null Coalescing Operator


PHP
David Egan

One of the goodies in PHP 7 is the null coalescing operator.

This provides an easy method of setting a variable if it exists (i.e. is not null), or setting it to a default if null.

Remember - PHP 7 is required!

Examples

The expression (expr1) ?? (expr2) evaluates to expr2 if expr1 is NULL, and expr1 otherwise — PHP Manual

<?php
// Null coalescing operator
$foo = $_POST['bar'] ?? 'baz';

// The pre PHP 7 way!
if(isset($_POST['bar'])){
  $foo = $_POST['bar'];
} else {
  $foo = 'baz'
}

// ...or pre-PHP 7 with a ternary:
$foo = isset($_POST['bar']) ? $_POST['bar'] : 'baz';

This is going to make setting defaults much neater and more readable.


comments powered by Disqus