Edit report at https://bugs.php.net/bug.php?id=62043&edit=1

 ID:                 62043
 Comment by:         phpmpan at mpan dot pl
 Reported by:        piotrekz5 at wp dot pl
 Summary:            new operator
 Status:             Open
 Type:               Feature/Change Request
 Package:            PHP options/info functions
 Operating System:   any
 PHP Version:        Irrelevant
 Block user comment: N
 Private report:     N

 New Comment:

---- BEGIN CODE ----
function ifNull($var, $value, $null = NULL) {
    return ($var !== $null)? $var : $value;
}
----- END CODE -----

Or even simpler to use and, unlike previous, working fine with undefined 
variables:

---- BEGIN CODE ----
function unNull(&$var, $value, $null = NULL) {
    if ($var === $null) {
        $var = $value;
    }
    return $var;
}
----- END CODE -----

If we drop the last argument even multiple operands version can be achieved:
---- BEGIN CODE ----
function nonNull() {
    return array_reduce(func_get_args(), function(&$a, $e) {
        return ($a === NULL && $e !== NULL)? $e : $a;
    });
}
----- END CODE -----
Any reason to not do this in userland?


Previous Comments:
------------------------------------------------------------------------
[2012-05-15 23:23:20] piotrekz5 at wp dot pl

Description:
------------
Hi,
Let's implement a new operator - '??' (used in c#).

The ?? operator is called the null-coalescing operator and is used to define a 
default value. It returns the left-hand operand if the operand is not null; 
otherwise it returns the right operand.


Test script:
---------------
example:
$var1 = null;
$var2 = null;
$var3 = $var1 ?? $var2; //$var3==null
$var4 = $var1 ?? 'default1'; //$var4=='default1'
$var5 = $var1 ?? $var2 ?? 'default2'; //$var5=='default2'
$var6 = $var2 ?? $var3 ?? $var4 ?? 'default3'; //$var6=='default1' since the 
first non-null value is $var4=='default1'



------------------------------------------------------------------------



-- 
Edit this bug report at https://bugs.php.net/bug.php?id=62043&edit=1

Reply via email to