mrmos Posted August 28, 2009 Share Posted August 28, 2009 Does anyone know if there is a php function to check if a set of numbers are in sequence? For example 1,2,3,4,5 or 23,24,25. If there isn't a function to do this could anyone suggest the best way to do this? Thanks Quote Link to comment Share on other sites More sharing options...
lemmin Posted August 28, 2009 Share Posted August 28, 2009 You could do this: if(array_intersect($needle, $haystack) == $needle) echo "Sequence is in array"; That matches even if they are out of order, though. If you want to match the order too, you can just keep them as a string (or put them into a string) and simply match it with strstr or regex. Quote Link to comment Share on other sites More sharing options...
ignace Posted August 28, 2009 Share Posted August 28, 2009 I think this should do the trick: function checkSequence($array) { $lowest = min($array); $inSequence = true; $sizeof = sizeof($array); for ($i = 0; $i < $sizeof; ++$i) { if ($lowest !== $array[0]) { $inSequence = false; break; } else if (isset($array[$i + 1]) && $array[$i] > $array[$i + 1]) { $inSequence = false; break; } } } return $inSequence; } Quote Link to comment Share on other sites More sharing options...
lemmin Posted August 28, 2009 Share Posted August 28, 2009 Oh woops. My brain added an 'a' in between your "in" and "sequence." Now you know how to check if a set of numbers are in a sequence, though. Quote Link to comment Share on other sites More sharing options...
mrmos Posted August 28, 2009 Author Share Posted August 28, 2009 Nice function! Maybe there's a small bug in it as with the following two arrays it returns true? $a1= array(1,2,3,4,5,6); $a2= array(3,4,5,12,15); Quote Link to comment Share on other sites More sharing options...
lemmin Posted August 28, 2009 Share Posted August 28, 2009 You could do it like this, too: function checkSequence($array) { $last = $array[0]; for($i=1;$i<sizeof($array);$i++) { if ($array[$i] != $last+1) return false; $last = $array[$i]; } return true; } Quote Link to comment Share on other sites More sharing options...
mrmos Posted August 28, 2009 Author Share Posted August 28, 2009 Great stuff lemmin, that works a treat!! Quote Link to comment Share on other sites More sharing options...
ignace Posted August 29, 2009 Share Posted August 29, 2009 An even simpler solution would be: if ($array == array_intersect(range(min($array), max($array)), $array))) { //in sequence } This will return true for: $a1= array(1,2,3,4,5,6); and returns false for: $a2= array(3,4,5,12,15); Quote Link to comment 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.