-1

I have an array that contains time stamps with associated "left" or "right" values:

array (size=237)
  1421439428 => string 'left' (length=4)
  1421439411 => string 'right' (length=5)
  1421439392 => string 'left' (length=4)
  [here goes the example TS from below]
  1421439380 => string 'right' (length=5)
  1421439358 => string 'left' (length=4)
  1421439329 => string 'right' (length=5)
  1421439240 => string 'right' (length=5)
  1421439234 => string 'left' (length=4)

Now I want to give a time stamp, e.g. 1421439391 (that is or is not in the keys) and I want to know, what is the most recent value. In this case "right". Even if it is closer to the left value I want to know the value below!

How is that possible (without a loop)?

With loop (based on function linked by Alex W):

function closest($array, $number) {  
  foreach ($array as $key=>$val) {
    if ($key <= $number) return $val;
  }
  return end($array); // or return NULL;
}
agoldev
  • 2,078
  • 3
  • 23
  • 38
  • 1
    It's possible with a loop. Unless we start performing intensive tasks in an iteration or nested looping, loops are cheap in processing power. Especially for this example. Why are you scared of them? – sjagr Jan 22 '15 at 16:15
  • Exactly how could you scan the array WITHOUT a loop? computers basically deal with a single bit of data at a time. an array is MULTIPLE bits of data. without a loop, there's no way to scan the array. even if you don't explicitly use a `for` or `foreach` in your code, SOMEWHERE there's going to have a be a loop to iterate the array's values and apply your tests. – Marc B Jan 22 '15 at 16:19
  • I know of solutions in R (stats language) that could to the trick. – agoldev Jan 22 '15 at 16:28
  • Why is that downvoted? – agoldev Jan 22 '15 at 16:46

1 Answers1

1

Obviously, to make this as efficient as possible you're going to first want to sort the array by the timestamps. Then, you will need to write your own closest function like this one.

Since you say you don't want to use a loop, which is how you would normally do it, you'll have to implement some kind of hashing function for the array indices that keeps the array sorted by timestamp value. Then, you can insert the timestamp value if it doesn't exist and then go to the next array index.

Community
  • 1
  • 1
Alex W
  • 37,233
  • 13
  • 109
  • 109
  • The array is sorted by timestamps. And I have a "closest" function, but I don't want the closest in both directions, but the closest past my given timestamp. – agoldev Jan 22 '15 at 16:27
  • The liked closest function doesn't allow for associative arrays like mine. – agoldev Jan 22 '15 at 16:41
  • @Toni The closest function should work fine for your array because it uses a foreach. That function also will not look at the closest in both directions, but will return what you want because it checks for a value that is greater than or equal to the `$number` parameter. – Alex W Jan 22 '15 at 19:27