PHP reads 1.10 value as 1.1 (0 at end of variable not honored)
This is hard for me to word, but easier for me to demonstrate:
I have a select option:
<option <?php if($frequency[$key]=='1.10'){echo "selected";}?> value='1.10'>1 every 10 days</option>
Really, $frequency[$key]=1.1; , but the above still shows up sele开发者_如何学编程cted. I've never seen this before, and didnt know it could happen. Any ideas on how to prevent this?
Working with php5. Thank you, Hudson
It's because PHP likes numbers so much that if either side of the comparison looks like a number, it'll try to make both operands numbers. This means your string gets casted to a float, and, indeed, becomes 1.1
.
To compare strings and make sure they're compared as strings, either use ===
(assuming your other operand is also a string), or use strcmp
.
if ($frenquency[$key] === '1.10')
if (strcmp($frenquency[$key], '1.10') == 0)
For more information, see the PHP manual on the Comparison Operators, page section 'Comparison with various types'.
You need to use the identity comparator ===
, not the equality comparator ==
.
$f = 1.1;
$s = '1.10';
$s == $f; // true
$s === $f; // false
Or, you could do an explicit string comparison:
strcmp($s, $f); // int(-1) -- they are not equal
Just an idea, but try "===" instead of "==" when you do the comparison, and put double quotes around 1.10 to force type as a string.
The manual tends to be pretty harsh when it comes to comparing floats. You should compare them as a string if you want a distinction between 1.1 and 1.10.
精彩评论