开发者

PHP reads 1.10 value as 1.1 (0 at end of variable not honored)

开发者 https://www.devze.com 2022-12-24 10:04 出处:网络
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&

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号