Strange (buggy?) array_search behaviour? [SOLVED]

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tomfra
Forum Contributor
Posts: 126
Joined: Wed Jun 23, 2004 12:56 pm
Location: Prague, Czech Republic

Strange (buggy?) array_search behaviour? [SOLVED]

Post 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

Last edited by tomfra on Thu Oct 26, 2006 3:50 am, edited 1 time in total.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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
tomfra
Forum Contributor
Posts: 126
Joined: Wed Jun 23, 2004 12:56 pm
Location: Prague, Czech Republic

Post by tomfra »

Thanks volka! I was not aware of this problem at all...

Tomas
Post Reply