Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Next Available Value in an Array, starting with a non-indexed value

Tags:

arrays

php

I've been stumped on this PHP issue for about a day now. Basically, we have an array of hours formatted in 24-hour format, and an arbitrary value ($hour) (also a 24-hour). The problem is, we need to take $hour, and get the next available value in the array, starting with the value that immediately proceeds $hour.

The array might look something like:

$goodHours = array('8,9,10,11,12,19,20,21).

Then the hour value might be:

$hour = 14;

So, we need some way to know that 19 is the next best time. Additionally, we might also need to get the second, third, or fourth (etc) available value.

The issue seems to be that because 14 isn't a value in the array, there is not index to reference that would let us increment to the next value.

To make things simpler, I've taken $goodHours and repeated the values several times just so I don't have to deal with going back to the start (maybe not the best way to do it, but a quick fix).

I have a feeling this is something simple I'm missing, but I would be so appreciative if anyone could shed some light.

Erik

like image 827
Erik Smith Avatar asked Mar 26 '10 18:03

Erik Smith


1 Answers

You could use a for loop to iterate over the array, until you find the first that is greater than the one you're searching :

$goodHours = array(8,9,10,11,12,19,20,21);
$hour = 14;

$length = count($goodHours);
for ($i = 0 ; $i < $length ; $i++) {
    if ($goodHours[$i] >= $hour) {
        echo "$i => {$goodHours[$i]}";
        break;
    }   
}

Would give you :

5 => 19



And, to get the item you were searching for, and some after that one, you could use something like this :

$goodHours = array(8,9,10,11,12,19,20,21);
$hour = 14;
$numToFind = 2;

$firstIndex = -1;
$length = count($goodHours);
for ($i = 0 ; $i < $length ; $i++) {
    if ($goodHours[$i] >= $hour) {
        $firstIndex = $i;
        break;
    }   
}

if ($firstIndex >= 0) {
    $nbDisplayed = 0;
    for ($i=$firstIndex ; $i<$length && $nbDisplayed<$numToFind ; $i++, $nbDisplayed++) {
        echo "$i => {$goodHours[$i]}<br />";
    }
}

Which would give you the following output :

5 => 19
6 => 20


Basically, here, the idea is to :

  • advance in the array, until you find the first item that is >= to what you are looking for
    • get out of that first loop, when found
  • If a matching item was found
    • loop over the array, until either its end,
    • or you've found as many items as you were looking for.
like image 180
Pascal MARTIN Avatar answered Oct 13 '22 00:10

Pascal MARTIN