Possible to chain comparison operators?

蹲街弑〆低调 提交于 2019-12-01 19:42:32

No, PHP doesn't have anything like this.

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.

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