Jump to content

[SOLVED] in_array error in a while loop


ProblemHelpPlease

Recommended Posts

I have a script that adds markers to a map based on latitude and longitude. To prevent to markers appearing on top of each other I am searching my database of markers and moving the marker to the right slightly if a current marker exists. The problem is that the markers stop moving to the right after the 3rd run through a while loop. I have managed to trace the error in the code.

 

Below is an example of the part of the code that fails.

 


<?php

$z = -8.1;

$arr = array("-2.1", "-11.1", "0.1", "-3.1", "-4.1", "-5.1", "-6.1", "-7.1", "-8.1", "-0.1", "1.1", "3.1", "2.1", "0.1");

while(in_array($z, $arr))

{

$z = $z + 1;

}

echo "final number ".$z . "<br>";

?>

 

This code should output the final number as -1.1 but when I run it it returns -3.1

 

If I use the same code but remove the - and the decimal place from the script then it works perfectly.

 

Any ideas as to what is wrong ???

Link to comment
Share on other sites

You are seeing a side effect of how numbers are stored internally. Decimal numbers can not be represented exactly as binary numbers, so the condition fails.

 

Change the loop to:

<?php
while(in_array(number_format($z,1), $arr)) {
$z++; 
}?>

 

Ken

Link to comment
Share on other sites

I thought it might be related to how many values could be stored.

 

The numbers that the main script is using very from -11.999999 to 3.999999(theyalways have 6 digits after the decimal place and need to maintain this format when output from the while loop), and I am tring to add 0.0005 to the value if it already exists in the array. Do I need to make a change to the "number_format($z,1)"

 

I haven't used number_format before so i'm still getting my head around how its working.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.