0

Any ideas how to shorten if statment in an elegant way.
My if statement:

 if(getfoo1() == getfoo2() &&  getfoo2() == 1)
 {

 }

EDIT:
I'm looking for something like:

if(getfoo1() == getfoo2() ==1)
{
}

But I suppose we can't do this.

JavaSa
  • 5,223
  • 15
  • 62
  • 106

5 Answers5

3
$a = getfoo1();
$b = getfoo2(); // less operations, while it not produces duplicate calls

if($a == $b && $b == 1){
    // do something
}
BlitZ
  • 11,836
  • 3
  • 49
  • 64
2
$variable = ((getfoo1() == getfoo2() && getfoo2() == 1) ? $value1 : $value2);

More elegant, combined:

$a = getfoo1();
$b = getfoo2();
$variable = (($a == $b && $b == 1) ? $value1 : $value2);
NoobEditor
  • 14,879
  • 17
  • 75
  • 106
Luka
  • 1,720
  • 3
  • 19
  • 29
1

Since we don't know the possible return values from the functions, if you assume they are integers then you can say:

$a = getfoo1();
$b = getfoo2();
if (($a * $b) === 1) { // strict equality for the win
    echo 'hi';
}

The result would only be true iff both $a AND $b are 1.

Another way:

$both = array(getfoo1(), getfoo2());
// use array_diff_assoc so it checks multiple occurrences of the same value
$diffCount = count(array_diff_assoc($both, array(1, 1))); 
if ($diffCount === 0) {
    echo 'hi';
}
Derek
  • 4,351
  • 2
  • 20
  • 33
0

Try this.

$a = getfoo1();
$b = getfoo2();
if( intval($a && $b) === 1) {
    echo 'hi';
}
RajivRisi
  • 398
  • 1
  • 11
0

Since anyway getfoo2() == 1 must be true, a better approach is to first check whether getfoo2() is equal to 1. If it false no matter about 2nd condition. But If you first check getfoo1() == getfoo2() and and then check getfoo2() == 1 you have to check 2 conditions all the times.

Therefore go for

$a = getfoo1();
$b = getfoo2();
if($b == 1 && $a == $b) 
{
     // logiv
}
else
{
}