-4

How to group repeated array values in an array using PHP?

I have an array like this

array[0]=203,
array[1]=204,
array[2]=204,
array[3]=203,
array[4]=203,
array[5]=205

I need results like

[203]=1,
[204]=2,
[203]=2,
[205]=1

i want the count of continuously repeating array values

rvandoni
  • 3,297
  • 4
  • 32
  • 46
BluezTechz
  • 55
  • 7
  • 1
    Show us what code you already have tried with. We certainly aren't going to do all of your work for you. – delboy1978uk Sep 10 '18 at 11:12
  • @MadhawaPriyashantha nope, OP needs to count sequences. – u_mulder Sep 10 '18 at 11:12
  • 5
    Your output makes it looks like you want this as a key=>value structure, but an array can't contain the same key more than once – iainn Sep 10 '18 at 11:12
  • Array can not contain same key more than once. So your expected outcome is not possible at all. What i am trying to say, check here:- https://eval.in/1055953 – Alive to die - Anant Sep 10 '18 at 11:16
  • The data you have provided in question is the hint for your answer...one more hint isset() function is very useful for your task. – Bhagwan Parge Sep 10 '18 at 11:17

3 Answers3

1
array[0]=203;
array[1]=204;
array[2]=204;
array[3]=203;
array[4]=203;
array[5]=205;

$new_array = array();
foreach ($array as $key => $value) {
    if(empty($new_array[$value])){
      $new_array[$value] = 1;
    }else{
      $new_array[$value]++;
    }
}
/*Now in the array $new_array you have the count of continuously repeating array values*/
C.Pietro
  • 89
  • 1
  • 9
1

One option to your expected output is to create a indexed array with the associative array below it.

This will create this kind of array:

array(4) {
  [0]=>
  array(1) {
    [203]=>
    int(1)
  }
  [1]=>
  array(1) {
    [204]=>
    int(2)
  }
  [2]=>
  array(1) {
    [203]=>
    int(2)
  }
  [3]=>
  array(1) {
    [205]=>
    int(1)
  }
}

This is not what you wanted but it is what is possible.

The code loops and keeps track of what the previous value is, if it's the same it will count up the value, else create a new indexed and associative array with value 1.

$array =[203,204,204,203,203,205];

$i=-1;
$prev = null;
$new=[];

foreach($array as $val){
    if($val != $prev){
        $i++;
    }
    if(!isset($new[$i][$val])){
        $new[$i][$val] =1;
    }else{
        $new[$i][$val]++;
    }

    $prev = $val;
}
var_dump($new);

https://3v4l.org/W2adN

Andreas
  • 23,610
  • 6
  • 30
  • 62
0

This can be done in one line of code using array_count_value function in php.

$arr[0]=203;
$arr[1]=204;
$arr[2]=204;
$arr[3]=203;
$arr[4]=203;
$arr[5]=205;

$result = array_count_values( $arr );
var_dump( $result );

output

array (size=3)
  203 => int 3
  204 => int 2
  205 => int 1
Al-Amin
  • 596
  • 3
  • 16