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.
Simple example where the $whoami variable is empty:
Or when $whoami is set.
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
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!
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
Bye bye notice! but an @ in your codebase….. ugh.
Assert all the things!
Awesome! No more notice!, but way to much lines of code….
In comes coalesce!
Bang! One line, no warnings, and no stupid @ suppression!