John Davidson

php - Why does 0.00 evaluates to true?

0 comments
Message:


I wanted to write a very simple function display some values only if they evaluate to true. So I wrote the piece of code below, and some test function calls...


function value_fff($value = false)
{
return $value ? $value : '';
}

echo value_fff('fsdfsdf') . '<br />';
echo value_fff('0.00') . '<br />';
echo value_fff('0') . '<br />';
echo value_fff(false) . '<br />';
echo value_fff(null) . '<br />';
echo value_fff('1') . '<br />';
echo value_fff() . '<br />';
echo value_fff(true) . '<br />';

My problem is that I get the following values:


fsdfsdf
0.00



1

1

So, it's obvious that 0.00 evaluates to true... Why is that happening? Indeed I'm in a locale that decimal separator is , instead of ., but is it that? And if yes, how am I supposed to deal with it?



My Answer:
'; // Output: fsdfsdf
echo value_fff(0) . ' '; // Output: 0
echo value_fff(0.00) . ' '; // Output: 0.00
echo value_fff('0') . ' '; // Output: 0
echo value_fff('') . ' '; // Output:
echo value_fff(null) . ' '; // Output:
echo value_fff(false) . ' '; // Output:

The reason why 0.00 evaluates to true in PHP is because PHP considers 0.00 as a non-empty value, which evaluates to true in a boolean context. In PHP, only the following values are considered false in a boolean context:

- The boolean value false itself
- The integer value 0
- The float value 0.0
- The empty string ''
- The string '0'
- An array with zero elements
- The special type NULL

Since 0.00 is not one of the values listed above, it evaluates to true in a boolean context.

Rate this post

3 of 5 based on 2494 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us