coalesce.php
This commit is contained in:
parent
d82c35138a
commit
acc214dfaa
50
php/coalesce.php
Normal file
50
php/coalesce.php
Normal 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);
|
Loading…
Reference in New Issue
Block a user