Page 1 of 1

Coalescing a coordinated conjunction set

Posted: Thu May 08, 2008 12:02 pm
by jefftanner
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:

Code: Select all

$v = $a['k1'] or $a['k2'] or $a['k3'] or 'default';
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:
  • 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'].
Using available PHP functions/operators, the only way I can figure out how the desired action of the coordinated conjunction set is, which is not as elegant as the pseudo code:

Code: Select all

$v = isset($a['k1']) ? $a['k1']
                                 : isset($a['k2']) ? $a['k2']
                                                            : isset($a['k3']) ? $a['k3']
                                                                                       : 'default';
Another way was by creating a function to perform the coalescing:

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');
 
Is there other elegant ways I can perform my desired operation?

Thanks

Jeff in Seattle

Re: Coalescing a coordinated conjunction set

Posted: Fri May 09, 2008 7:13 am
by Weirdan
as there's no such functionality provided by php natively, your function looks ok (though you may clarify it further by returning null (return null) if no sufficient argument was found)