Possible to chain comparison operators?

前端 未结 2 1742
心在旅途
心在旅途 2021-01-19 06:43

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

相关标签:
2条回答
  • 2021-01-19 07:13

    No, PHP doesn't have anything like this.

    0 讨论(0)
  • 2021-01-19 07:28

    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.

    0 讨论(0)
提交回复
热议问题