Justin Justin - 2 days ago 5
PHP Question

2 or more arrays from a list

I am quite not able to get the logic for my requirement.

Lets consider I have an array

Array
(
[0] => 1
[1] => 1
[2] => 2
[3] => 1
[4] => 3
[5] => 3
)


I would like to split the below array on the basis if the array element matches its previous element.
i.e in the above example value at [1] matches the value at [0]. Hence put it into the same array as [0]. Now check if the value at [2] matches the value at [1] if it matches put it into the same array, if not put it into a different array. The process continues.

Below is an example of the desired outpout.

Array
(
[0] => 1
[1] => 1
)
Array
(
[0] => 2
)

Array
(
[0] => 1
)
Array
(
[0] => 3
[1] => 3
)


Thanks for your help in advance.

Justin

Answer

you can obtain that result in a loop checking on previous element. the output can be an array of arrays! (or anything you would prefer.. do your thing here)

$array1 = array(1, 1, 2, 1, 3, 3);
$output_array=array();
$previous_value="";
$output_array_index=0;
foreach ($array1 as $value) {
    if($value != $previous_value){
        $output_array_index+=1;
    }
    $output_array[$output_array_index][]=$value;
    $previous_value=$value;
}
print_r($output_array);

so, let me know if you need more pointers! array logic is fun, and php will let you do alot, out of the box. though this specific need is not covered, have a look when you have a minute @ the manual, it'll save you time in the future, guarantee http://php.net/manual/en/ref.array.php

Comments