0

I am not sure what I am doing wrong, but the inline if statement always returns true, even if it is not supposed to.

I have the following statement

<?php echo ($total == 'Scratched' || ($total > 0 && $total < 65)) ? 'ffefef' : 'f7f7f7'; ?>

Just above this statement, I echo $total and that echoes out 0

At the top of the page I define <?php $total = 0; ?>, so $total is defined as an integer.

The above if statement only returns false if $total > 64 but not when total is 0

Thanks in advance

Rickus Harmse
  • 576
  • 1
  • 6
  • 21
  • 1
    @MarkBaker, but there is no nested ternaries in the question – Alex Blex Mar 02 '17 at 09:27
  • Possible duplicate of [How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?](http://stackoverflow.com/questions/80646/how-do-the-php-equality-double-equals-and-identity-triple-equals-comp) – TZHX Mar 02 '17 at 09:44

5 Answers5

6

It's because 0 == 'Scratched'

 // Strict comparison fixes it
 echo ($total === 'Scratched' || ($total > 0 && $total < 65)) ? 'ffefef' : 'f7f7f7'; 
smarber
  • 4,201
  • 4
  • 28
  • 64
3

This is working

<?php 
$total = 0;
echo ($total === 'Scratched' || ($total > 0 && $total < 65)) ? 'ffefef' : 'f7f7f7';
?>
Hossam
  • 1,025
  • 8
  • 18
3

Base on your given situation. If I understand it quite well. Your state wont accept it as false if its 0.

The above code should work. But try explicitly adding the not equal zero:

echo ($total === 'Scratched' || ($total > 0 && $total < 65 && $total != 0)) ? 'ffefef' : 'f7f7f7';

Also added === to make sure the first statement of type string.

Reyan Tropia
  • 130
  • 10
1

Use === to compare $total === 'Scratched' and that will fixed

 <?php echo ($total === 'Scratched' || ($total > 0 && $total < 65)) ? 'ffefef' : 'f7f7f7'; ?>
Rafiqul Islam
  • 1,526
  • 1
  • 11
  • 25
0

You can try strict comparison:

<?php echo ($total === 'Scratched' || ($total > 0 && $total < 65)) ? 'ffefef' : 'f7f7f7'; ?>

Because of comparing a numeric variable over a string, the string is evaluated in a numeric context and represents 0.

You can take a look at the folowing post: Comparing String to Integer gives strange results

Community
  • 1
  • 1