Variable equal to itself if the result of the logic is false

3

Consider the following code:

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

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

I did this, but I wonder if there is still another way:

$a = $b;
$a = $a > $c ? $c : $a;
    
asked by anonymous 29.08.2014 / 22:27

2 answers

2

It's easier to understand by assigning values in the 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
    
29.08.2014 / 23:22
2

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

$a = $b;
if( $a > $c )
 $a = $c;
    
30.08.2014 / 01:40