verification of e in php

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 greater than the others. The variable $curva_b must be less than $curva_a and greater than $curva_c . The variable $curva_c always has to be smaller than the others.

I made the code in php, but I did not like it very much, it's working, but I think there's a better way to do that.

Follow 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";
}
    
asked by anonymous 27.03.2017 / 14:35

2 answers

5

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 adjunctive 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 satisfied. p>

Or, to facilitate, add the expressions:

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

To test, I made a small 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, when you change the second value in $tests , referring to the expected result, $expected , a assert error will be fired for that test.

See working at Repl.it , or Ideone .

    
27.03.2017 / 15:08
1

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

if(!($curva_a > $curva_b && $curva_b > $curva_c) ){
 /*ERRO*/ 
}
    
27.03.2017 / 16:31