OK, I’m a bit late to the party on this, but it’s worth saying that the new null coalescing feature of PHP 7 has already saved a lot of mind-numbing code.
The scenario is all-too familiar. You are processing a form submission with some fields that don’t always turn up in $_POST, like unchecked checkboxes. That, or maybe you have to deal with query strings that may or may not be supplied, so one of the $_GET array elements might not be present.
In days gone by, ignorant even of the ternary operator, I would have done something like this:
$name = 'default'; if (isset($_GET['name'])) $name = $_GET['name']; echo "Name is set to $name";
By the way, that snippet also shows how I usually try to avoid if .. else, by setting the default first. It’s just a personal thing.
Then one fine day I became aware of the ternary operator. Everything could be done on one line! Still annoying to have to type $_GET twice, but still.
$name = isset($_GET['name']) ? $_GET['name'] : 'default'; echo "Name is set to $name";
And now, PHP 7 has brought the mysteriously-named null coalescing operator, which shrinks the code even more.
$name = $_GET['name'] ?? 'default'; echo "Name is set to $name";
So, assign the $_GET array element, but if that isn’t set, use the default supplied. Still legible, and certainly a time-saver. I’m using it all the time now, and even changing old code to use this structure.
By the way, PHP 7.4 introduces the even-more-mysteriously-named Null coalescing assignment operator, using the ??= symbol. As its name suggests, it combines the condition and the assignment. For me, the downside is that the condition is applied to the same variable that will receive the assignment. This means that you’d end up doing this:
$_GET['name'] ??= 'default'; $name = $_GET['name']; echo "Name is set to $name";
Well, another pet hate of mine is modifying $_GET and $_POST, so I’ll not be using this last structure, at least, not in the scenario I’ve been discussing.