Ben Davidow
Ben Davidow

Reputation: 1215

Counter Array in PHP

I want to write a function that returns a counter array. That is, given an array of integers $A, in which the integers are in the range (0...$m) it should return an array of size $m + 1 in which each index has the number of occurrences of that index number in $A.

For instance, if:

$A = array(1, 4, 2, 2, 4, 2);
$m = 4;

It should output:

array(0, 1, 3, 0, 2)

I'm wondering if there is a built-in function to do this in PHP.

In python it would look something like:

def counting(A, m):
    n = len(A)
    count = [0] * (m + 1)
    for k in xrange(n):
        count[A[k]] += 1
    return count

Upvotes: 1

Views: 495

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 78994

New version:

$result = array_replace(array_fill(0, $m+1, 0),
                        array_slice(array_count_values($A), 0, $m-1, true));
  • Replace an array of zeros with length $m+1 with a count of the values of $A up to length $m.

Original version:

$result = array_fill(0, $m+1, 0);

foreach($A as $i) {
    if(isset($result[$i])) {
        $result[$i]++;
    }
}
  • Create a $result array of zeros with length $m+1
  • Loop array $A and increment $result index of $A value

Obviously if you want a function just wrap code in:

function counting($A, $m) {
    //code
    return $result;
}

Upvotes: 0

Ravinder Reddy
Ravinder Reddy

Reputation: 3879

Try the below code

function count_array($array,$m){
   // count values
   $count_values = array_count_values($array);
   // loop for $m times
   for($i=0;$i<=$m;$i++){
       // check if there exits a key in the array
       if(array_key_exists($i,$count_values)){
           $result_array[$i] = $count_values[$i];
       }else{
           $result_array[$i] = 0;
       }
    }
    return $result_array;
}

$A = array(1, 4, 2, 2, 4, 2);
$m = 4;
$result = count_array($A,$m);

Out Put:

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

Upvotes: 0

Chin Leung
Chin Leung

Reputation: 14921

You can try this:

$a = array(1, 4, 2, 2, 4, 2);
$m = 4;

function counting(Array $a, $m){
    // Create our result array
    $result = array();

    // Make sure m is an integer for version before PHP 7, otherwise return an empty array
    if(!is_int($m))
        return $result;

    // Get the count of each occurence in the array
    $counts = array_count_values($a);

    // Loop through each number of m
    for($i=0; $i<=$m; $i++)
        $result[$i] = isset($counts[$i]) ? $counts[$i] : 0;

    return $result;
}

The result of var_dump(counting($a, $m)):

array(5) {
    [0]=>
        int(0)
    [1]=>
        int(1)
    [2]=>
        int(3)
    [3]=>
        int(0)
    [4]=>
        int(2)
}

Upvotes: 2

Related Questions