0

So I have an array containing multiple values like this

$input_array = array('45', '21', '45', '45', '45', '29', '35', '35', '21');

Now I want to split it into multiple arrays to group adjacent values if they are similar. For Example, the above array should split into 6 different arrays

$input_array_1 = array('45');

$input_array_2 = array('21');

$input_array_3 = array('45', '45', '45');

$input_array_4 = array('29');

$input_array_5 = array('35', '35');

$input_array_6 = array('21');

is this something possible in PHP?

7
  • 2
    is this something possible in PHP? - fortunately yes it is. Have you tried anything yourself yet? Commented Aug 12, 2019 at 18:41
  • Yes, I tried using array_chunk() function but I have no idea how can I dynamically change its 'size' parameter and run the function again every time. I googled for an answer but did not find anything which can help me solve this issue Commented Aug 12, 2019 at 18:47
  • write the code you tried to solve your problem and we can help you Commented Aug 12, 2019 at 19:09
  • Duplicate - stackoverflow.com/q/47402882/296555 Commented Aug 12, 2019 at 19:14
  • @waterloomatt That doesn't handle the adjacent aspect of this problem, does it? I mean, wouldn't it group all the 45s together in the above example? Commented Aug 12, 2019 at 19:17

6 Answers 6

1

I don't recommend the use of dynamic number of resulting vars like you asked in your question. It's better to have the result inside an array. This way you can cycle through the array indexes, instead of guessing how many $input_array_(number) your code generated.

$input_array = array('45', '21', '45', '45', '45', '29', '35', '35', '21');

$result = [];
$index = 0;
$processedElement = null;
foreach ($input_array as $currentElement) { 
    if ($processedElement != $currentElement) {
        $index++;   
    }
    $result[$index][] = $currentElement;
    $processedElement = $currentElement;
}

Printing $result will give you:

Array
(
    [0] => Array
        (
            [0] => 45
        )
    [1] => Array
        (
            [0] => 21
        )
    [2] => Array
        (
            [0] => 45
            [1] => 45
            [2] => 45
        )
    [3] => Array
        (
            [0] => 29
        )
    [4] => Array
        (
            [0] => 35
            [1] => 35
        )
    [5] => Array
        (
            [0] => 21
        )
)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a simple foreach to loop though, then check the last value in the new array and append, to get the global vars, create an array first then extract, as shown below.

<?php
$input_array = array('45', '21', '45', '45', '45', '29', '35', '35', '21');

$result = [];

foreach ($input_array as $key => $value) {
    // get last item in array
    $last = end($result);

    // does last == this one
    if (isset($last[0]) && $last[0] === $value) {
        // append it
        $result['input_array_'.count($result)][] = $value;
    } else {
        // create new
        $result['input_array_'.(count($result)+1)][] = $value;
    }
}

print_r($result);

// to conform to question (not required)
extract($result);
print_r($input_array_3);

Result:

Array
(
    [input_array_1] => Array
        (
            [0] => 45
        )

    [input_array_2] => Array
        (
            [0] => 21
        )

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

    [input_array_4] => Array
        (
            [0] => 29
        )

    [input_array_5] => Array
        (
            [0] => 35
            [1] => 35
        )

    [input_array_6] => Array
        (
            [0] => 21
        )

)

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

https://3v4l.org/RHsY4

Comments

0

You can try. Hope it helps you

$input_array = array('45', '21', '45', '45', '45', '29', '35', '35', '20');

$allChunk = [];
$Chunk = [];
echo "<pre>";
foreach ($input_array as $value) {
    $chunk[] = $value;
    if(in_array(next($input_array),$chunk)) {
        continue;
    }
    $allChunk[] = $chunk;
    unset($chunk);
}
var_dump($allChunk);

Comments

0

This method builds up a list of similar values, then when the value changes it adds this list to the end of the output array. The only thing is the first time in it has an empty list, rather than exclude adding it, I use array_shift() to remove this blank entry at the end...

$input_array = array('45', '21', '45', '45', '45', '29', '35', '35', '21');
$output = [];
$temp = [];
foreach ( $input_array as $value )  {
    if ( $value != ($temp[0]??'') ){
        $output[] = $temp;
        $temp = [$value];
    }
    else    {
        $temp[] = $value;
    }
}
array_shift($output);
$output[] = $temp;
print_r($output);

gives the output (truncated)...

Array
(
    [0] => Array
        (
            [0] => 45
        )

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

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

Comments

0
$input_array = array('45', '21', '45', '45', '45', '29', '35', '35', '21');

$arr=array();
$prev_value=null;
foreach ($input_array as $key => $value) {
    if($value==$prev_value){
       array_push($arr[count($arr)-1],$value); 
    }
    else{
        $prev_value=$value;
        array_push($arr,array($value));
    }
}

print_r($arr);

Comments

0

As demonstrated at Group associative elements by keys with contiguous dates to create an array of associative arrays, you won't need to keep track of indexes in the result array if you push references into the result array representing each group. This way you only push repeating values into the references. Demo

$result = [];
$last = null;
foreach ($array as $v) {
    if ($last !== $v) {
        unset($ref);
        $result[] =& $ref;
    }
    $ref[] = $v;
    $last = $v;
}
var_export($result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.