PHP: Either function because PHP lacks a good "or"

PHP lacks a good "or" comparison operator. Neither the or operator, nor the || return a value. I wrote a function that will take two (or more) variables and return the first one that has a non-empty value.

$limit = $array_count || 15;       // true (bad!)
$limit = $array_count or 15;       // true (also bad!)
$limit = either($array_count, 15); // 15 (good!)
function either() {
    $items = func_get_args();

    // Return the first non-empty item
    foreach ($items as $x) {
        if (!empty($x)) {
            return $x;
        }
    }

    return null;
}
Leave A Reply
All content licensed under the Creative Commons License