coalesce.php

This commit is contained in:
Anthony Axenov 2022-01-11 08:18:50 +08:00
parent d82c35138a
commit acc214dfaa
Signed by: anthony
GPG Key ID: EA9EC32FF7CCD4EC

50
php/coalesce.php Normal file
View File

@ -0,0 +1,50 @@
<?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
* @see https://gist.github.com/anthonyaxenov/f30961849d5bfb2651901af120607694
* @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);