Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Lorna Mitchell:
New in PHP 7: null coalesce operator
Sep 30, 2015 @ 15:51:52

Lorna Mitchell has a post to her site talking about a new addition to PHP in the upcoming major release of PHP 7 - the null coalesce operator. Despite its slightly confusing name, the operator is very handy for certain use cases with the ternary syntax.

Not the catchiest name for an operator, but PHP 7 brings in the rather handy null coalesce so I thought I'd share an example. In PHP 5, we already have a ternary operator, which tests a value, and then returns the second element if that returns true and the third if it doesn't. [...] There is also a shorthand for that which allows you to skip the second element if it's the same as the first one.

[...] In PHP 7 we additionally get the ?? operator which rather than indicating extreme confusion which is how I would usually use two question marks together instead allows us to chain together a string of values.

She includes an example of this new operator in use, chaining together a simple expression and showing the resulting output. It's a little confusing at first, but then if you remember it reads left to right it clears it up a bit.

tagged: null coalesce operator php7 feature example

Link: http://www.lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator


Trending Topics: