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

2

5 Answers 5

6

It's because 0 == 'Scratched'

 // Strict comparison fixes it
 echo ($total === 'Scratched' || ($total > 0 && $total < 65)) ? 'ffefef' : 'f7f7f7'; 
Sign up to request clarification or add additional context in comments.

Comments

3

This is working

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

Comments

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.

Comments

1

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

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.