One of the new features of PHP7 is the coalesce operator. Basically it creates a default value for your variable when your given variable is null.

Coalesce basics

Simple example where the $whoami variable is empty:

<?php
$username = $whoami ?? 'awesome';
echo $username; // will echo 'awesome'

Or when $whoami is set.

<?php
$whoami = 'arno';
$username = $whoami ?? 'awesome';
echo $username; // will echo 'arno'

So basically they created a feature for you that saves about ~10 characters typing. NICE!

Using coalesce for validation

However having to type less code is always an improvement, I personally think coalesce solves the issue of keeping your array validation simple without making crap code.

Example with simple not empty validation

<?php
function whoami(array $nestedArray) {
	if ( empty($nestedArray['some']['name'])) {
		throw new SomeException('Expected name');
	}
	
	return $nestedArray['some']['name'];
}

This validates if the name is empty, if it is it throws an exception. Easy enough.

With assertion library

Alltho the if statement is proper PHP code, I feel it is easier to guard your input validation via an assertion library.

Example with beberlei/assert beberlei/assert

This also solves writing an extra PHP unit test where it could go wrong. Less is more!

<?php
function whoami(array $nestedArray) {
	Assertion::notEmpty($nestedArray['some']['name'], 'Empty name');
	
	return $nestedArray['some']['name'];
}

The assertion library picks up the if empty check, and throws an assertion exception. Great! code is easier.

However what is always anoying, PHP will raise a E_NOTICE on $nestedArray[‘some’][‘name’]. A missing index when it is empty. For production not a problem, I assume warnings are suppressed. But when running unit tests, it will expose the notices. And I dont like them!

Using an @ to supress warnings

<?php
function whoami(array $nestedArray) {
	Assertion::notEmpty(@$nestedArray['some']['name'], 'Empty name');
	
	return $nestedArray['some']['name'];
}

Bye bye notice! but an @ in your codebase….. ugh.

Assert all the things!

<?php
function whoami(array $nestedArray) {
	Assertion::isArray($nestedArray);
	Assertion::keyExists($nestedArray, 'some');
	Assertion::isArray($nestedArray['some']);
	Assertion::keyExists($nestedArray['some'], 'name');
	Assertion::notEmpty($nestedArray['some']['name'], 'Empty name');
	
	return $nestedArray['some']['name'];
}

Awesome! No more notice!, but way to much lines of code….

Argh!

In comes coalesce!

<?php
function whoami(array $nestedArray) {
	Assertion::notEmpty($nestedArray['some']['name'] ?? '', 'Empty name');
	
	return $nestedArray['some']['name'];
}

Bang! One line, no warnings, and no stupid @ suppression!