Doubt in the comparison of variables

Asked

Viewed 88 times

0

There is another way to develop this comparison?

$numero = 1234;
$a = 1111;
$b = 2222;
$c = 3333;
$d = 4444;

if ($numero == $a or $numero == $b or $numero == $c or $numero == $d) {
    echo "O número existe";
    } else {
    echo "Não existe o número";
}

I wonder if there’s another way to manipulate that comparison

  ($numero == $a or $numero == $b or $numero == $c or $numero == $d)
  • 1

    Beware the difference between or and || is the priority. see manual logical operators

  • In the original code the variables receive the values $numero = 0.00005670;
$a = 0.00008756;
$b = 0.00006745;
$c = 0.00006754;
$d = 0.00008734; What’s the difference? The two wouldn’t work the same way in this situation?

1 answer

3


If you need to find (compare) a value, you can transform these variables($a, $b, $c e $d) in an array and then search with the in_array(), the first argument($numero) is what you want to seek and the second($arr) in which variable this should be done.

$numero = 1234;
$a = 1111;
$b = 2222;
$c = 3333;
$d = 4444;

$arr = array($a, $b, $c, $d);

if (in_array($numero, $arr)) {
    echo "O número existe";
} else {
    echo "Não";
}
  • Depending on the need, it may be interesting to use the third parameter of the in_array - Strict - with the true value, so that it also does type checking.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.