PHP - count consecutive repeated elements in array in the same sequence as they are

PHP - count consecutive repeated elements in array in the same sequence as they are

Related searches

I need to count consecutive repeated elements in the array, but if they are non consecutive I want to count them also, to have them in the same sequence as they are.

For example I have flowing array:

$array = Array ('a','b','a','a','a','c','c','b','b','a','a','a','a');

if I use array_count_values function example:

print_r(array_count_values($array));

Output will be:

Array ( [a] => 8 [b] => 3 [c] => 2 )

But I need to get output like this:

element   counted value
    a       1
    b       1
    a       3
    c       2
    b       2
    a       4

I would appreciate if anybody could help me with this issue?

Thank you.


You can iterate over the array, counting values while they are the same, and pushing a value to the result array when they are different:

$result = [];
$count = 0;
$current = $array[0];
for ($i = 0; $i < count($array); $i++) {
    if ($array[$i] == $current) {
        $count++;
    }
    else {
        $result[] = array($current, $count);
        $count = 1;
    }
    $current = $array[$i];
}
$result[] = array($current, $count);
print_r($result);

Output:

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

Demo on 3v4l.org

Count consecutive pairs of same elements, Given an array arr[], the task is to count the number of pairs formed by consecutive elements in which both of the elements in a pair are same. No two consecutive elements in the given array are equal. C++; Java; Python3; C#; PHP values of all adjacent elements � Find the K-th Permutation Sequence� count() - Count all elements in an array, or something in an object array_unique() - Removes duplicate values from an array array_values() - Return all the values of an array


Starting with an array with the first item from the source (and a count of 1), this then starts from the second item and checks if it matches the one in the current output. Adding 1 if it matches or adding a new entry if it doesn't...

$array = Array ('a','b','a','a','a','c','c','b','b','a','a','a','a');
$output = [ ["element" => $array[0], "count" => 1 ] ];
$outputPoint = 0;
for ( $i = 1, $count = count($array); $i < $count; $i++ )   {
    if ( $array[$i] == $output[$outputPoint]["element"] )  {
        $output[$outputPoint]["count"]++;
    }
    else    {
        $output[++$outputPoint] = ["element" => $array[$i], "count" => 1 ];
    }
}
print_r($output);

Which outputs...

Array
(
    [0] => Array
        (
            [element] => a
            [count] => 1
        )

    [1] => Array
        (
            [element] => b
            [count] => 1
        )

    [2] => Array
        (
            [element] => a
            [count] => 3
        )

    [3] => Array
        (
            [element] => c
            [count] => 2
        )

    [4] => Array
        (
            [element] => b
            [count] => 2
        )

    [5] => Array
        (
            [element] => a
            [count] => 4
        )

)

Count of only repeated element in a sorted array of consecutive , Count of only repeated element in a sorted array of consecutive elements The task is to find length of the sequence of repeated element. Input : arr[] = {1, 2, 3, 4, 4, 4, 5, 6} Output : 4 3 Repeated element is 4 and it appears 3 times. k-th missing element in sorted array � Last duplicate element in a sorted array � Count � If the array is sorted and if max-difference of two adjacent elements is 1, then the length of the repeated sequence is n – 1 – (array [n-1] – array) Value of the element. To the value, we do Binary Search.


This loops through the array and increments the number of elements in $count.

$array = ['a','b','a','a','a','c','c','b','b','a','a','a','a'];

$count = [];
$crt   = -1;
foreach($array ?? [] as $element) {
    if($crt == -1 || $count[$crt]["element"] != $element) {
        $count[++$crt] = ["element" => $element, "counted_value" => 1];
    } else {
        $count[$crt]["counted_value"]++; 
    }
}

The array looks like:

Array
(
    [0] => Array
        (
            [element] => a
            [counted_value] => 1
        )

    [1] => Array
        (
            [element] => b
            [counted_value] => 1
        )

    [2] => Array
        (
            [element] => a
            [counted_value] => 3
        )

    [3] => Array
        (
            [element] => c
            [counted_value] => 2
        )

    [4] => Array
        (
            [element] => b
            [counted_value] => 2
        )

    [5] => Array
        (
            [element] => a
            [counted_value] => 4
        )

)

array_count_values - Manual, Returns an associative array of values from array as keys and their count as value. Throws E_WARNING for every element which is not string or integer. Removes duplicate values from an array; array_values() - Return all the values of an In order to apply array_map with callback checking for localised values like city� The count () function returns the number of elements in an array.


$out = array();
$cnt = -1;
foreach($array as $val)
{
   if(in_array($val,$out))
   {
        $out[] = $var;
        $finalArr[$cnt]['cnt'] = count($out);
   }else{
        $out = array();
        $out[] = $val;
        $finalArr[] = array('ele'=>$val,'cnt'=>count($out));
        $cnt++;
   }
}
print_r($finalArr);

range - Manual, range — Create an array containing a range of elements If a step value is given, it will be used as the increment between elements in the sequence. step� Find the two repeating elements in a given array. You are given an array of n+2 elements. All elements of the array are in range 1 to n. And all elements occur once except two numbers which occur twice. Find the two repeating numbers. For example, array = {4, 2, 4, 5, 2, 3, 1} and n = 5.


substr_count - Manual, PHP 5, PHP 7). substr_count — Count the number of substring occurrences It outputs a warning if the offset plus the length is greater than the haystack length . Return Values � Simply convert the haystack and the needle to the same case (upper or lower). a simple version for an array needle (multiply sub- strings): count (mixed $array_or_countable [, int $mode = COUNT_NORMAL ]) : int Counts all elements in an array, or something in an object. For objects, if you have SPL installed, you can hook into count () by implementing interface Countable.


Improve this sample solution and post your code through Disqus. Previous: Write a program in C to count a total number of duplicate elements in an array. Next: Write a program in C to merge two arrays of same size sorted in decending order.


I'd like to know a way I could go through each individual element in the array, and getting a value for how many steps the number stays at the same value. For instance, for this example, the output I would be looking for would be