Possible to chain comparison operators?

风格不统一 提交于 2019-12-01 21:40:02

问题


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.


回答1:


No, PHP doesn't have anything like this.




回答2:


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.



来源:https://stackoverflow.com/questions/15070831/possible-to-chain-comparison-operators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!