acctman
acctman

Reputation: 4349

Making a long IF / operator statement shorter

Can someone provide some tips for avoiding long operator statements like the one below... can NULL, '', and -1 be grouped together

if(($row['ios'] == null && $row['android'] == null)||
($row['ios'] == null && $row['android'] == -1) || 
($row['ios'] == null && $row['android'] == '') || 
($row['ios'] == '' && $row['android'] == null) || 
($row['ios'] == '' && $row['android'] == '') || 
($row['ios'] == '' && $row['android'] == '-1') || 
($row['ios'] == '-1' && $row['android'] == null) || 
($row['ios'] == '-1' && $row['android'] == '') || 
($row['ios'] == '-1' && $row['android'] == '-1')){
$desktop_count++;
}

Upvotes: 1

Views: 50

Answers (2)

MonkeyZeus
MonkeyZeus

Reputation: 20747

You can take advantage of PHP's type casting to convert your variables into integers:

if( (int)$row['ios'] <= 0 && (int)$row['android'] <= 0 )
{
    $desktop_count++;
}

No mess, no fuss.

You could forgo the explicit (int) casting but using explicit casting helps to avoid ambiguity when you read this code at a later time.

For reference, below are the var_dump()s of the values which you are working with:

var_dump( (int)'' );
var_dump( (int)'-1' );
var_dump( (int)null );

int(0)
int(-1)
int(0)

Upvotes: 2

Andreas
Andreas

Reputation: 23958

In_array is a better alternative.

if(in_array($row['ios'], [null, "", -1]) && in_array($row['android'], [null, "", -1])){
   $desktop_count++;
}


As Felippe below says it can be a benefit to use an variable.

$invalidValues = [null, "", -1];
if(in_array($row['ios'], $invalidValues) && in_array($row['android'], $invalidValues)){
       $desktop_count++;
}

Upvotes: 3

Related Questions