Created
June 8, 2015 08:20
-
-
Save tyxla/d289a3f1a48c7e58d34c to your computer and use it in GitHub Desktop.
Function that returns the largest array of consecutive numbers. Uses numerical keys.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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