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

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.