feub feub - 9 days ago 7
PHP Question

Loop through an array of integers and break every 1000

I am working with activity tracking files. I want to browse through a GPX file and do something for every 1000m milestone. But the device does not necessarily record a GPS track right at 1000m, 2000m, etc, so I cannot use something like

$distance % 1000
. What I want is to detect each time a 1000m milestone has passed, by performing an action at the milestone just after.

Here is an example of the distance tracked:

0
3
28

997
1003
1027

1998
2006

2989
3001


and so on. In this example, I'd need to perform an action when 1003 has been reached, then 2006 and then 3001.

How can I trigger an event every time the data passes a multiple of 1000?

Answer

If your data is coming in a string then you could explode the string by what ever the delimiter is and then loop it.

<?php
$string = "0 3 28 36 42 66 73 80 103 125 997 1003 1027 2006 3001";
$data= explode( ' ', $string );

$multiple = 1;
foreach( $data as $value )
{
  if( (int)$value > ( 1000 * $multiple ) ) 
  {
    // Passed a 1000 marker
    echo $value."\n";
    $multiple++;
  }
}

Output:

1003
2006
3001