Pregunta

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.

¿Fue útil?

Solución

No, PHP doesn't have anything like this.

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top