Edit report at https://bugs.php.net/bug.php?id=39553&edit=1
ID: 39553 Comment by: jeffvanb at u dot washington dot edu Reported by: greg at mtechsolutions dot ca Summary: Add coalesce() and coalesce_strict() functions Status: Open Type: Feature/Change Request Package: Feature/Change Request Operating System: all PHP Version: 5.2.0 Block user comment: N Private report: N New Comment: 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. Previous Comments: ------------------------------------------------------------------------ [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