You get a bonus - 1 coin for daily activity. Now you have 1 coin

Null-coalescence operator - php Two question marks ??

Lecture



Two question marks that go in a row without a space (first appeared in php7) - this is nothing more than:

Null-coalescence operator (operator of union with null)

Solves a common problem in PHP.
It occurs if we want to assign a value to a variable that is assigned to another variable, but if the value of the last variable was not assigned, then assign some explicit default value.

Often manifested when working with user input.

Before PHP 7:

?

one

2

3

four

five

6

if (isset ($ foo)) {

$ bar = $ foo;

} else {

// assign $ bar the value of 'default' if $ foo is NULL

$ bar = 'default';

}

In PHP 7 (now available)):

one

$ bar = $ foo ?? 'default';

Can be used with a chain of variables:

one

$ bar = $ foo ?? $ baz ?? 'default';


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)