Variable equal to itself if the logic result is false

Asked

Viewed 154 times

3

Consider the following code:

$a = $b > $c ? $c : $b;

The question is, if $b is a set of operations, if the logic result $b > $c is false, I will have to repeat the entire existing operation in $b.

I did it this way, but I wonder if there’s another way:

$a = $b;
$a = $a > $c ? $c : $a;
  • 2

    this is an "abuse" of the ternary operator since its code is less efficient than a if(). It makes no sense to make the logical comparison and an assignment that is not necessary. if($a > $c) $a=$c; (assigns nothing in else (for not having the same)).

  • @Kyllopardiun Else would be necessary in the first example but not in the second. The question is the first example, if $b is a set of operations, it is not legal to rewrite everything if the result of logic is false, that is the question.

  • 1

    Philip, I cannot understand your question. It seems to me something obvious: if I want to keep a logical result to some extent what I must do? Store and that’s exactly what you did.

2 answers

2

It is easier to understand by assigning values to variables:

$b = (2 * 4); // 8

$c = 6;

$a = $b;

if ($b > $c) $a = $c; // true, redefine o valor de $a = $c

echo $a; // resulta 6

//-----------------//

$b = (2 * 4); // 8

$c = 10;

$a = $b;

if ($b > $c) $a = $c; // false, não faz nada, e mantem $a = $b

echo $a; // resulta 8

2

Your second example is the best to do, since, you say that to have the value $b you have to make calculations the best is to store temporarily in the variable so as not to waste time repeating the calculation. However I would not use the ternary operator since if you do it will be much easier to understand for the human species:

$a = $b;
if( $a > $c )
 $a = $c;

Browser other questions tagged

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