1

Example I have array like this:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 1
    [4] => 5
    [5] => 5
    [6] => 5
    [7] => 6
    [8] => 7
    [9] => 8
    [10] => 9
)

And my question is, how to create new array like this. So create new array for the same value:

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

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

    [2] => 6
    [3] => 7
    [4] => 8
    [5] => 9
)

Please help me and sory for my bad english.

0

2 Answers 2

2
$result = [];
foreach (array_count_values($array) as $value => $occurrences) {
    $result[] = $occurrences == 1 ? $value : array_fill(0, $occurrences, $value);
}

See http://php.net/array_count_values. In fact, this may really be what you're looking for; I don't see the point in repeating the same value many times.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @deceze... very thanks :) But how if same value not only 1, example 1,1,1 and 5,5,5. This code is same?
0

Try this one using array_count_values

<?php

$tr = Array(1,1,1,1,5,5,5,6,7,8,9,10);

$array= array_count_values($tr);
var_dump($array);


$arry1 = array();
foreach($array as $key =>$val){
 if ($val>1){
     $tmp =array();
     for($i= 0;$i<$val;$i++){
       $tmp[] =$key;
     }
     $arry1[] =$tmp;
 }
 else{
     $arry1[] =$key;
 } 
}

var_dump( $arry1);
?>

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.