galvin Posted May 21, 2011 Share Posted May 21, 2011 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? Quote Link to comment https://forums.phpfreaks.com/topic/237020-how-to-find-next-available-array-item/ Share on other sites More sharing options...
requinix Posted May 21, 2011 Share Posted May 21, 2011 A foreach loop is the one you want to use. Make sure the array is sorted first - use sort() if it might not be. Quote Link to comment https://forums.phpfreaks.com/topic/237020-how-to-find-next-available-array-item/#findComment-1218290 Share on other sites More sharing options...
PaulRyan Posted May 21, 2011 Share Posted May 21, 2011 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. Quote Link to comment https://forums.phpfreaks.com/topic/237020-how-to-find-next-available-array-item/#findComment-1218294 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.