Which would be considered the better/faster running/proper way of doing this?
<?php
if($a == 4 && $b == 8)
{
$c = "car";
}
if($a == 5 && $b == 3)
{
$c = "car";
}
if($a == 5 && $b == 2)
{
$c = "car";
}
?>
OR
<?php
if($a == 4 && $b == 8 || $a == 5 && $b == 3 || $a == 5 && $b == 2)
{
$c = "car";
}
?>
I don’t have benchmark of it… but for more human readable way could be something like this (or say I would do in this way):
if(in_array($a, array(4,5)) && in_array($b, array(8,3,2))){
echo "Car";
}
Be verrrrry careful with that joined one, scout1idf.
if($a == 4 && $b == 8)
if($a == 5 && $b == 3)
if($a == 5 && $b == 2)
if($a == 4 && $b == 8 || $a == 5 && $b == 3 || $a == 5 && $b == 2)
these two statements may not be equivalent.
if(($a == 4 && $b == 8) || ($a == 5 && $b == 3) || ($a == 5 && $b == 2))
WOULD be equivalent.
Raju: While streamlined, your code does not give the desired result (a = 4, b = 2 is ‘false’ (not ‘car’) in his logic, but the in_array tests would return true.
What you could do to use in_array is define it as:
$valid = array("4,8","5,3","5,2");
if(in_array($a.",".$b,$valid) {
echo "Car";
}
It’s hard without knowing context, but from a readability POV…
<?php
$isFourAndEight = $a == 4 && $b == 8;
$isFiveAndThree = $a == 5 && $b == 3;
$isNineAndSeven = $a == 9 && $b == 7;
if($isFourAndEight || $isFiveAndThree || $isNineAndSeven){
$c = 'car';
}
rpkamp
June 24, 2011, 12:53pm
5
Yes they are, && has a higher precedence than ||, so internally
if($a == 4 && $b == 8 || $a == 5 && $b == 3 || $a == 5 && $b == 2)
will be executed as if it were
if(($a == 4 && $b == 8) || ($a == 5 && $b == 3) || ($a == 5 && $b == 2))
As for the original question, you could also use:
if($a == 4 && $b == 8)
{
$c = "car";
}
else if($a == 5 && $b == 3)
{
$c = "car";
}
else if($a == 5 && $b == 2)
{
$c = "car";
}
which is faster than the if (a) if (b) if (c) but just as fast as the (a || b || c)
(brownie points to anyone who can tell why)
Well okay, in this example they are, Scallio, the point was more to the intimation that if(A), if(B) == if(A || B) may not be true, and it’s better practice to say if((A)||(B)).
rpkamp
June 24, 2011, 1:05pm
7
Yeah you’re right about that. It’s just that I kinda dislike parentheses so I tend to avoid them if at all possible
(okay I dislike everything that is more verbose than need be)
Thanks for the info everyone.
I got side tracked by a virus so I didn’t have time to respond.