What is the null coalescing operator in PHP7?

PHP: What is the null coalescing operator in PHP7?

The null coalescing operator is two question marks: ??. It is used to replace some ternary operations. Here is an example:

  1. // old way
  2. $var = isset($_GET['variable']) ? $_GET['variable'] : "default_val";
  3.  
  4. // new way - null coalescing:
  5. $var = $_GET["variable"] ?? "default_val";

Both of the above lines do the same thing: they set $var to $_GET['variable'] if it is set (if it passes isset()), but if not then it sets $var to 'default_val'.

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about What is the null coalescing operator in PHP7?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the PHP language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to fix the MySQL related "Specified key was too long error" error in Laravel

How to find out which php.ini file PHP is using?

What are generators in PHP, and how do they compare to arrays?

How to select what columns to return when calling ::all()

How to check if an object or variable is an array, in JS?

How to redirect your website to a new domain/location in .htaccess

How to return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

What is the difference between integration and unit tests?

Force trailing slash (redirect if no trailing slash exists) in .htaccess

How to get table column names from a database table in Eloquent?