Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coalesce function for PHP?

Many programming languages have a coalesce function (returns the first non-NULL value, example). PHP, sadly in 2009, does not.

What would be a good way to implement one in PHP until PHP itself gets a coalesce function?

like image 926
mikl Avatar asked Jun 18 '09 15:06

mikl


People also ask

What is null coalescing operator PHP?

Null coalescing operator ¶ The null coalescing operator ( ?? ) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null ; otherwise it returns its second operand.

What is coalesce function in MySQL?

The MySQL COALESCE() function is used for returning the first non-null value in a list of expressions. If all the values in the list evaluate to NULL, then the COALESCE() function returns NULL. The COALESCE() function accepts one parameter which is the list which can contain various values.

What is use of NULL coalesce operator?

Uses of Null Coalescing Operator: It is used to replace the ternary operator in conjunction with the PHP isset() function. It can be used to write shorter expressions. It reduces the complexity of the program. It does not throw any error even if the first operand does not exist.

How do you set a variable to NULL in PHP?

In PHP, a variable with no value is said to be of null data type. Such a variable has a value defined as NULL. A variable can be explicitly assigned NULL or its value been set to null by using unset() function.


2 Answers

There is a new operator in php 5.3 which does this: ?:

// A echo 'A' ?: 'B';  // B echo '' ?: 'B';  // B echo false ?: 'B';  // B echo null ?: 'B'; 

Source: http://www.php.net/ChangeLog-5.php#5.3.0

like image 140
Kevin Avatar answered Oct 13 '22 18:10

Kevin


PHP 7 introduced a real coalesce operator:

echo $_GET['doesNotExist'] ?? 'fallback'; // prints 'fallback' 

If the value before the ?? does not exists or is null the value after the ?? is taken.

The improvement over the mentioned ?: operator is, that the ?? also handles undefined variables without throwing an E_NOTICE.

like image 29
flori Avatar answered Oct 13 '22 18:10

flori