Coalescing a coordinated conjunction set
Posted: Thu May 08, 2008 12:02 pm
Hi
I want to do a short-circuit evaluation of a coordinated conjunction set where it returns the first non-NULL value in the list, or NULL if there are no non-NULL values.
Short-circuit evaluation is where the next argument to the right is only evaluated if the first argument does not suffice to determine the value of the expression.
This would be a similar operation as MySQL COALESCE().
I am not looking for a boolean result from the coordinated conjunction set.
To clarify what I am looking for, here is an example in pseudo code:
If $a['k1'] is not set or NULL, then it would move right to assess the value of $a['k2'], and so on until the assessment got to the end of the coordinated conjunction set returns 'default' value.
I tried the pseudo code in PHP, but it would only evaluate the value of the first argument in the coordinated conjunction set: $a['k1']. For example:
Another way was by creating a function to perform the coalescing:
Is there other elegant ways I can perform my desired operation?
Thanks
Jeff in Seattle
I want to do a short-circuit evaluation of a coordinated conjunction set where it returns the first non-NULL value in the list, or NULL if there are no non-NULL values.
Short-circuit evaluation is where the next argument to the right is only evaluated if the first argument does not suffice to determine the value of the expression.
This would be a similar operation as MySQL COALESCE().
I am not looking for a boolean result from the coordinated conjunction set.
To clarify what I am looking for, here is an example in pseudo code:
Code: Select all
$v = $a['k1'] or $a['k2'] or $a['k3'] or 'default';I tried the pseudo code in PHP, but it would only evaluate the value of the first argument in the coordinated conjunction set: $a['k1']. For example:
- If $a['k1'] is set and not NULL, then $v would be assigned the value within $a['k1'].
- If $a['k1'] is not set or NULL, then $v would be NULL. Thus ignoring any further evaluation of any of the arguments to the right of $a['k1'].
Code: Select all
$v = isset($a['k1']) ? $a['k1']
: isset($a['k2']) ? $a['k2']
: isset($a['k3']) ? $a['k3']
: 'default';Code: Select all
function coalesce() {
$args = func_get_args();
foreach ($args as $arg) {
if (!empty($arg)) {
return $arg;
}
}
return $args[0];
}
# Example usage:
$v = coalesce($a['k1'], $a['k2'], $a['k3'], 'default');
Thanks
Jeff in Seattle