Setting default values for requests the easy way

PHP 7 introduced the Null Coalesce Operator, and this is a very neat addition to PHP in practice. It will let you write code that is much easier to read and much more concise.

You don’t have to wrestle anymore with isset() and ternary operators.

Just write this:

$offset = $_GET['offset'] ?? 0;

It there is now offset parameter in the GET request, $offset will be assigned the default value 0.

This is much like the way you can do that in Python or Javascript.

Before 7 you needed to write this in PHP:

if (isset($request->input['offset'])) {
$offset = $request->input['offset'];
} else {
$offset = 0;
}

Leave a Reply



Categories
-->
Archives
Links