|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2006-11-19 09:36 UTC] 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
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Tue Oct 28 01:00:01 2025 UTC |
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.