With PHP 7 finalised and almost here I thought I’d take a look and pick out a few of my favourite new features that it introduced. I do a lot of my daily work in PHP but do know a few other languages fairly well – there are some things being added that PHP has been lacking for a long time so, to me, this feels like a big catch up.
Null Coalescing
Despite is being a relatively simple thing this is by far my favourite addition. Anyone familiar with JavaScript will know that you can assign a variable using the first non-null value from a list – an example will make this make more sense
var mainHeading = document.querySelector('h1');
var subHeading = document.querySelector('h2');
var targetHeading = mainHeading || subHeading || 'fallback_value';
This snippet will leave targetHeading
being equal to mainHeading
or if that’s null subHeading
. super useful in loads of cases. PHP can do something similar
$target_heading = (!empty($main_heading)) ? $main_heading : $sub_heading;
The obvious limitation here is that this is limited to two input variables (note the lack of the fallback value) whereas the JavaScript syntax allows for any number. To get the same thing in PHP you have to use a quite large statement
if (!empty($main_heading)){
$target_heading = $main_heading;
}else if (!empty($sub_heading)){
$target_heading = $sub_heading;
}else{
$target_heading = 'fallback_value';
}
Much longer. You could use the array functions to make this a little shorter
$target_heading = array_shift(array_filter([$main_heading, $sub_heading, 'fallback_value']));
bit too hacky.
This all changes with version 7 with the null coalescing operator – which does the exact same thing as the JavaScript example. It looks not too dissimilar to the ternary operator
$target_heading = $main_heading ?? $sub_heading ?? 'fallback_value';
It seems minor but this is such a massive time saver in so many places – I’m pretty happy. Next one to follow.