Skip to content

Instantly share code, notes, and snippets.

@tyxla
Created June 8, 2015 08:20
Show Gist options
  • Save tyxla/d289a3f1a48c7e58d34c to your computer and use it in GitHub Desktop.
Save tyxla/d289a3f1a48c7e58d34c to your computer and use it in GitHub Desktop.
Function that returns the largest array of consecutive numbers. Uses numerical keys.
<?php
function get_largest_consecutive_number_array($array) {
$result = array();
$total_elements = count($array);
foreach ($array as $key => $element) {
$temp = array($element);
$next_key = $key + 1;
while($next_key < $total_elements) {
if ($array[$next_key] === $array[$next_key - 1] + 1) {
$temp[] = $array[$next_key];
$next_key++;
} else {
break;
}
}
$total_temp = count($temp);
$total_result = count($result);
if ( $total_temp > $total_result ) {
$result = $temp;
} elseif( $total_temp == $total_result && $temp[0] > $result[0] ) {
$result = $temp;
}
}
return $result;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment