Page 1 of 1

Strange (buggy?) array_search behaviour? [SOLVED]

Posted: Thu Oct 26, 2006 3:05 am
by tomfra
OK, this is odd and I simply got to be missing something here...

Code: Select all

$search_value = 1.57;
$range_r = range(1.55, 1.75, 0.01);
$is_in_range = array_search($search_value , $range_r);

echo "<pre>"; print_r($range_r); echo "</pre>";

var_dump($is_in_range);
Through the range() function I create a simple array:

Code: Select all

Array
(
    [0] => 1.55
    [1] => 1.56
    [2] => 1.57
    [3] => 1.58
    [4] => 1.59
    [5] => 1.6
    [6] => 1.61
    [7] => 1.62
    [8] => 1.63
    [9] => 1.64
    [10] => 1.65
    [11] => 1.66
    [12] => 1.67
    [13] => 1.68
    [14] => 1.69
    [15] => 1.7
    [16] => 1.71
    [17] => 1.72
    [18] => 1.73
    [19] => 1.74
    [20] => 1.75
)

Now, if $search_value is anything from 1.55 (i.e. the first value in the range array) up to 1.62 (key #7), array_search can find it just fine. But if $search_value is anything from 1.63 ((key #8) up to the last array element, it returns false.

This is odd... Have you experienced anything like this? I know I may not have the newest PHP 5 tree version but maybe I am just missing something here.

Thanks!

Tomas


Posted: Thu Oct 26, 2006 3:11 am
by volka
Its a precision problem

Code: Select all

<?php
$a = 1.62 + 0.01;
$b = 1.63;

echo "$a==$b ", ($a==$b) ? 'yes':'no';
?>
take a look at the "Floating point precision" box at http://www.php.net/manual/en/language.types.float.php

Posted: Thu Oct 26, 2006 3:49 am
by tomfra
Thanks volka! I was not aware of this problem at all...

Tomas