Reputation: 3096
I have some code that finds 3 consecutive numbers from an array and outputs them.
What I would like it to do now is be able to tell it how many numbers to find. I did think about putting a for loop inside the outside for loop but i don't see it working properly.
How can i get this iteration to run X times until X is met?
if(isset($arr[$i+1]))
if($arr[$i]+1==$arr[$i+1])
echo 'I found it:',$arr[$i],'|',$arr[$i+1],'|',$arr[$i+2],'|',$arr[$i+3],'<br>';
exit;
This is what i have so far
for($i=0; $i < sizeof($arr); $i++) {
if(isset($arr[$i+1]))
if($arr[$i]+1==$arr[$i+1])
{
if(isset($arr[$i+2]))
if($arr[$i]+2==$arr[$i+2])
{
if(isset($arr[$i+3]))
if($arr[$i]+3==$arr[$i+3])
{
echo 'I found it:',$arr[$i],'|',$arr[$i+1],'|',$arr[$i+2],'|',$arr[$i+3],'<br>';
exit;
}//if3
}//if 2
}//if 1
}
Upvotes: 2
Views: 2790
Reputation: 41820
Instead of looking forward repeatedly, you could just loop through the array, comparing the current value to the previous value to see if the values are consecutive, while keeping track of the current consecutive count. Consecutive numbers should be appended to an array, and non-consecutive numbers should reinitialize the array. When you reach the desired count of consecutive numbers, you can return the result.
function find_consecutive($array, $count) {
$consecutive = array();
$previous = null;
foreach ($array as $value) {
if ($previous !== null && $value == $previous + 1) {
$consecutive[] = $value;
if ($found == $count) {
return "I found it: " . implode("|", $consecutive) . "<br>";
}
} else {
$consecutive = array($value);
$found = 1;
}
$previous = $value;
$found++;
}
}
Upvotes: 3