Jump to content

how to find next available array item?


galvin

Recommended Posts

Say i have an array (called $myarray) and it has 10 numbers in it like this...

 

1

2

4

8

9

10

12

14

15

18

 

Now in my code, I get a number and lets say for this example it is "5". 

 

I need to see if that number is in the array --easy enough using in_array()--, but if it is NOT in the array, I need to find the next available number in the array that is greater than my starting number of 5  (which would be "8" in this example).

 

But what is the best way to find this number (i.e. 8 in this example)?

 

I imagine I need to somehow loop through but i'm not sure which loop is the best to use and i'm generally confusing the hell out of myself (which is frustrating because this is probably rather simple to do :)).

 

Can anyone help guide me in the right direction? 

Link to comment
Share on other sites

Try something like the following, provding you don't need the array again it will work, if you do then I could figure something else out, just let me know :)

 

<?PHP

  $array = array('1','2','4','8','9','10','12','14','15','18');

  $number = 5;

  if(!in_array($number,$array)) {
    array_push($array,"$number");
    sort($array);
    foreach($array AS $value) {
      if($value == $number) {
        $number = current($array);
      }
    }
  }

  echo $number;
?>

 

Regards, PaulRyan.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.