Concise conditional structure with multiple comparisons

-1

How to compare three items with the same result? I'm currently doing the following, but so the code design does not look elegant.

if ($title == 0 && $squad == 0 && $level == 0) {
   return true;
}

What I'm wanting is something like:

if ($title && $squad && $level == 0) {
   return true;
}
    
asked by anonymous 05.04.2018 / 18:21

4 answers

3

You have put the PHP and Java tags, so I will give solutions in both languages.

In PHP:

$t = array_unique(array($title, $squad, $level));
if (count($t) == 1 && in_array(0, $t)) {
    return true;
}

In Java:

Set<Integer> s = Set.of(title, squad, level);
if (s.size() == 1 && s.contains(0)) {
    return true;
}

Other in Java:

if (IntStream.of(title, squad, level).allMatch(x -> x == 0)) {
    return true;
}
    
05.04.2018 / 18:56
5

If if continues on things that are not return false :

if (!$a && !$b && !$c) {
   return true;
}

... outros statements ...

Alternative to the whole code of the question, in PHP, if it is to return from qq form:

return !$a && !$b && !$c;

But the "inelegant" is relative, I find it much worse compact than it is readable, than clear as the original.

Just be careful with PHP. Depending on the type, because strange things happen, especially when you "invent fashion."

Note: As mentioned by @rray in the comments, this expression is equivalent to the above:

if ( !($a || $b || $c) ) ...
    
05.04.2018 / 22:00
1

Our friend Miguel made the following reply, but for some reason he did not want to post:

<?php

$title = 0;
$squad = 0;
$level = 0;

var_dump([$title, $squad, $level] == [0,0,0]);

$level = 1;

var_dump([$title, $squad, $level] == [0,0,0]);

See here working on ideone.

    
05.04.2018 / 21:51
0

If it's something constant in the project, I'd recommend creating a function for it. Including, it would be possible, in addition to the suggestions in the other answers, use the function array_reduce :

function has_same_value($array, $value) {
    return array_reduce($array, function ($carry, $item) use ($value) {
        return $carry && ($item == $value);
    }, true);
}

So, just do:

return has_same_value([$title, $squad, $level], 0);

See working at Repl.it | Ideone

Or:

function array_all($array, $callback) {
    foreach($array as $item) {
        if (!$callback($item)) {
            return false;
        }
    }

    return true;
}

Which benefits from the short circuit of logical expressions, stopping to iterate in the first false item.

$title = 0;
$squad = 0;
$level = 0;

$resultado = array_all([$title, $squad, $level], function ($item) {
    return $item == 0;
});

var_dump($resultado);  // bool(true)

See the Repl.it | Ideone

    
06.04.2018 / 01:35