Jump to content

[SOLVED] does an array function like this exist?


tryingtolearn

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

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.