< and > check in php

Asked

Viewed 55 times

1

Well I have to do a 3 variable check, with the following rule.

Variables:

$curva_a
$curva_b
$curva_c

Rules:

The variable $curva_a always has to be bigger than the others. The variable $curva_b has to be smaller than the $curva_a and greater than the $curva_c. The variable $curva_c always has to be smaller than the others.

I did the code in php, but I didn’t like it much, it’s working, but I think there’s some better way to do it.

Follows the code:

$erro =  false;

// Verifica os valores das curvas
if (($curva_a < $curva_b) || ($curva_a < $curva_c)) {
    $erro = true;
}
if (($curva_c > $curva_a) || ($curva_b < $curva_c)) {
    $erro = true;
}
if ($curva_c > $curva_a) {
    $erro = true;
}

// Verifica erro
if ($erro === true) {

    echo "erro";
}

2 answers

6


If your intention is to compare three values, the final order should always be the same:

$curva_a > $curva_b > $curva_c

You can only compare the adjascent values:

if ($curva_a <= $curva_b) // Erro!
if ($curva_b <= $curva_c) // Erro!

Ensure that $curva_a is greater than $curva_b and that $curva_b is greater than $curva_c, already ensures that $curva_a is greater than $curva_c and therefore all conditions are met.

Or, to make it easier, join the expressions:

if ($curva_a <= $curva_b || $curva_b <= $curva_c) {
    // Erro!
}

To test, I made a little code:

// [[$a, $b, $c], $expected]
$tests = [
  [[1, 2, 3], false], // a < b < c, erro!
  [[1, 3, 2], false], // a < b > c, erro!
  [[2, 1, 3], false], // a > b < c, erro!
  [[3, 2, 1], true],  // a > b > c, ok!
  [[1, 1, 1], false], // a = b = c, erro!
  [[2, 2, 1], false], // a = b > c, erro!
  [[2, 1, 1], false], // a > b = c, erro!
  [[2, 1, 2], false]  // a > b < c, erro!
];

foreach($tests as $i => $test)
{
  list($curva_a, $curva_b, $curva_c) = $test[0];
  $expected = $test[1];

  assert(($curva_a <= $curva_b || $curva_b <= $curva_c) == !$expected, "Erro no teste {$i}");
}

If all tests pass, no output is produced. However, by changing the second value in $tests, referring to the expected result, $expected, a mistake of assert will be shot for that test.

See working on Repl.it, or in the Ideone.

  • if( ! ($curva_a > $curva_b > $curva_c) ){ /missed/ } It would solve already do not think ?

  • 1

    @Bartolomeus.Gusella, PHP does not support this type of syntax.

1

You can use a check only from $curva_a with $curva_b and $curva_b with $curva_c

if(!($curva_a > $curva_b && $curva_b > $curva_c) ){
 /*ERRO*/ 
}

Browser other questions tagged

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