Jump to content

Recommended Posts

Maybe I am missing it but say you have an array that contains 15 numbers

array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)

 

when a page loads it is going to use 5 of the numbers at random out of the array,

 

could be

1 - 2 - 6 - 9 - 11

or

8 - 11 - 12 - 13 -14

 

but what I need to find is if those #s are in any consecutive order

ex

1-2-3-4-5

or

7-8-9-10-11

 

Ive read through the array function page but dont see a anything for this,

is there an array function that does this?

Something like this would work:

 

<?php
function isConsecutive($array) {
   $previous = array_shift($array);
   foreach($array as $value) {
      if($value != $previous + 1) {
         return false;
      }
      $previous = $value;
   }
   return true;
}
?>

Something like this would work:

 

<?php
function isConsecutive($array) {
   $array = array_shift($array);
   $array = array_chunk($array, 5);

   $first = true;

   foreach($array as $value) {

      if ( isSet($first) ){
         $previous = $value - 1;
         $first    = false;
      }

      if($value != $previous + 1) {
         return false;
      }
      $previous = $value;
   }
   return true;
}
?>

function isConsecutive($array) {
   if (!is_array($array)
      return false;
   sort($array);
   $min = reset($array);
   $max = end($array); 
   if ($array == range($min, $max))
      return true;
   return false;
} // end isConsecutive

 

Thanks Crayon Violet

That worked also

 

Thorpe - If it returns true it is going to 1 set of additional checks, if false it goes to a different set of checks,

it is sorting the array so even if it starts at 13 - its just going to take the five integers and see if they are in consecutive order.

 

Thanks for the help, once again seems like I was making harder than it needed to be haha

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.