PHP-Coalesce

This little function has proven very useful to me. If you are familiar with the SQL coalesce function you would know that it takes the first non null argument. This can be useful for variable setting and such.

The javascript interpretation would be
var myVar = var1 || var2 || '0';

Which would take the first non null variable. And if var1 and var2 are both null it sets it to 0. Well I need this same functionality in php multiple times and I found a little function which does it very well.

function coalesce() {
$args = func_get_args();
foreach ($args as $arg) {
if (!empty($arg)) {
return $arg;
}
}
return $args[0];
}

To use just pass in
$myVar = coalesce($var1, $var2, '0');

And it has the same effect as the above javascript statement.