Skip to content

Instantly share code, notes, and snippets.

@anthonyaxenov
Created September 23, 2020 10:14
Show Gist options
  • Save anthonyaxenov/f30961849d5bfb2651901af120607694 to your computer and use it in GitHub Desktop.
Save anthonyaxenov/f30961849d5bfb2651901af120607694 to your computer and use it in GitHub Desktop.
[PHP] Simple equivalent of Oracle's coalesce()
<?php
/**
* Simple php equivalent of Oracle's coalesce()
*
* It can be used as simple oneline-alternative to switch or if operators in many
* cases without difficult logic. For example, get first non-empty value from bunch of vars:
*
* echo coalesce($var1, $var2, $var3, ...);
*
* is alternative to:
*
* if ($var1) {
* return $var1;
* } elseif ($var2) {
* return $var2;
* } elseif ....
*
* or
*
* return $var1 ?? $var2 ?? $var3 ...
*
* @see https://docs.oracle.com/cd/B28359_01/server.111/b28286/functions023.htm
* @author Anthony Axenov
* @return mixed|null
*/
function coalesce() {
foreach (func_get_args() as $arg) {
if (is_callable($arg)) {
$arg = call_user_func($arg);
}
if ($arg !== null) {
return $arg;
}
}
return null;
}
//usage:
$var1 = null;
$var2 = function() use ($var1) {
return $var1;
};
$var3 = 3;
$var4 = '4';
$result = coalesce($var1, $var2, $var3, $var4);
var_dump($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment