Php – 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?

Best Solution

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';