How to add string into array in PHP?

Viewed 41

I have these for loop to determine consecutive number. What I achieve so far is to print the output in string.

$arr    = [1,2,3,6,11,5,4,8,9,3];   
for($start=0; $start<=count($arr); $start++){ 

    for($end=$start+1; $end<=count($arr); $end++){ 
        
        $total = $arr[$end] - $arr[$start];
        if($total == 1){
            echo 'Number is '.$arr[$start].','.$arr[$end].'<br/>'; 
        } else {
            echo ''; 
        }
        $arr[$start++]; 

    }
}

My goal is to add the output into array.

I tried to use multidimensional array but no output display.

$arr    = [1,2,3,6,11,5,4,8,9,3];   

$arr3 = [];
for($start=0; $start<=count($arr); $start++){ 

    for($end=$start+1; $end<=count($arr); $end++){ 
        
        $total = $arr[$end] - $arr[$start];
        if($total == 1){ 

            $arr2 = array();
            $arr2[] = $arr[$start].','.$arr[$end].'';
            $arr3[] = $arr2; 

        } else {
             
        }
        $arr[$start++]; 

    }
}

echo '<pre>';
print_r($arr3);
echo '</pre>';
exit;

Appreciate if someone can help me. Thanks.

2 Answers

You can better sort() the input array first. This way, collecting all consecutive elements would get much simpler. If value at any index isn't +1 of the previous one, we add the $temp in our $results array and start a new $temp from this index.

Snippet:

<?php

$arr = [1,2,3,6,11,5,4,8,9,3];   

$result = [];
sort($arr);
$temp = [];
for($i = 0; $i < count($arr); ++$i){
    if($i > 0 && $arr[ $i ] !== $arr[$i - 1] + 1){
        $result[] = implode(",", $temp);
        $temp = [];
    }
    $temp[] = $arr[$i];
    if($i === count($arr) - 1) $result[] = implode(",", $temp);
}

print_r($result);

Online Demo

you can simply use array functions, if sorting is important to you as @nice_dev said, you must sort your array before.

$arr    = [1,2,3,6,11,5,4,8,9,3];  
$cons = [] ;
while (array_key_last($arr) != key($arr)) {
    if ((current($arr)+1) == next($arr)) {
        prev($arr);
        $cons[] = current($arr) . ',' . next($arr);
    }
}
print_r($cons);

the output will be :

Array
(
   [0] => 1,2
   [1] => 2,3
   [2] => 8,9
)
Related