Possible to chain comparison operators?

2020-04-08 01:14发布

I've been thus far unable to find this information in the official PHP docs, or on this site. So, that may mean I'm searching under the wrong terms, or it is not supported. What am I looking for? I'll describe it...

Let's say I have the following comparisons in PHP:

if (($a == $b) && ($b == $c))
    doSomething();
else
    doSomethingElse();

if (($d < $e) && ($e < $f))
    doSomething();
else
    doSomethingElse();

Does PHP have some kind of syntax to chain the comparisons together without the explicit AND-ing of two different comparisons? For example, is something like this possible:

if ($a == $b == $c)
    doSomething();
else
    doSomethingElse();

if ($d < $e < $f)
    doSomething();
else
    doSomethingElse();

Note that I am looking for a syntactic shorthand in the language. I know that I can easily write a function for each of these chained comparisons, but this is a kludgy work-around, and not desired. For example:

function chainedGreaterThan($args)
{
    for ($i = 0; $i < count($args) - 1; $i++)
        if ($args[$i] <= $args[$i + 1])
            return false;
    return true;
}

This technically would work, but is not a syntactic shorthand given by the language.

2条回答
时光不老,我们不散
2楼-- · 2020-04-08 01:39

You could do something awful like this when you have very large amounts of things to compare.

<?php
$arr = [1, 2, 3];
$less_than = function($a, $b) {
    return $a < $b;
};
$greater_than = function($a, $b) {
    return $a > $b;
};

function apply_operator($arr, $operator) {
    for ($i = 0; $i < sizeof($arr) - 1; $i++) {
        if (!$operator($arr[$i], $arr[$i + 1])) {
            return false;
        }
    }
    return true;
}

var_dump(apply_operator($arr, $less_than)); // true
var_dump(apply_operator($arr, $greater_than)); // false

But for greater/less than you can just sort and compare to the original, and for equal you can check the size of array_unique.

查看更多
相关推荐>>
3楼-- · 2020-04-08 01:48

No, PHP doesn't have anything like this.

查看更多
登录 后发表回答