Req #39553 [Opn->Csd]: Add coalesce() and coalesce_strict() functions
Edit report at https://bugs.php.net/bug.php?id=39553&edit=1
ID: 39553
Updated by: requinix@php.net
Reported by: greg at mtechsolutions dot ca
Summary: Add coalesce() and coalesce_strict() functions
-Status: Open
+Status: Closed
Type: Feature/Change Request
-Package: Feature/Change Request
+Package: *General Issues
Operating System: all
PHP Version: 5.2.0
-Assigned To:
+Assigned To: requinix
Block user comment: N
Private report: N
New Comment:
PHP 5.3 modified the ternary operator to support $a ?: $b as a false-y coalesce (and chaining them
works as expected) but will still warn on undefined offsets.
PHP 7 introduces ?? which coalesces not-set/null and won't warn for undefined offsets.
'' ?: 0 ?: 1 -> 1
0 ?: null ?: false ?: '' -> ''
0 ?? null ?? false ?? '' -> 0
Previous Comments:
------------------------------------------------------------------------
[2013-09-27 23:16:34] jeffvanb at u dot washington dot edu
These functions would be useful, but they can both be implemented as PHP
methods. An even more useful implementation would be a language construct
similar to isset that returns the value of the first variable that isset:
$b = false;
$c = true;
echo coalesce($a,$b,$c); // false
unset($b);
echo coalesce($a,$b,$c); // true
$a = 'hello';
echo coalesce($a,$b,$c); // 'hello'
I don't believe the above method can be implemented as a PHP function because
something like
echo coalesce($a['test'],$b,$c);
would throw an undefined key error instead of returning $b.
------------------------------------------------------------------------
[2006-11-19 09:36:39] greg at mtechsolutions dot ca
Description:
------------
I see value in adding two functions to php: coalesce() and coalesce_strict().
Both of these would take an arbitrary number of arguments, and use the first non-empty() or non-null
value (respectively).
For example:
$username = coalesce($_POST['username'], $_COOKIE['username'],
'guest');
Parameters passed would not have to be defined (eg, the above script should not generate notices if
E_STRICT is on and $_POST['username'] is undefined), and undefined variables would be
treated as null.
Reproduce code:
---------------
// The PHP (close) equivalents:
function coalesce() {
$max = func_num_args();
for ($i = 0; $i < $max-1; $i++) {
$value = func_get_arg($i);
if (!empty($value)) {
return $value;
}
}
return func_get_arg($max-1);
}
function coalesce_strict() {
$max = func_num_args();
for ($i = 0; $i < $max-1; $i++) {
$value = func_get_arg($i);
if ($value !== null) {
return $value;
}
}
return func_get_arg($max-1);
}
Expected result:
----------------
coalesce('',0,1); // returns 1
coalesce(0,null,false,''); // returns '' (last value)
coalesce_strict(0,null,false,''); // returns 0
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=39553&edit=1
Thread (3 messages)