tags:

views:

44

answers:

4

Hello,

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 selected. 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

A: 

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.

danp
You could also consider a separator other than a period - then you won't have the problem, because it won't be misinterpreted as a float.
Michael Madsen
In PHP: `"1.10" == "1.1"` is true.
nickf
+5  A: 

It's because PHP likes numbers so much that if it sees something that looks like a number on either side of the comparison, it'll try to make the operands numbers instead of their actual type. This means you 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'.

zneak
A: 

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.

Alex Ciminian
+1  A: 

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
nickf