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
AbraCadaver
79.2k7 gold badges75 silver badges91 bronze badges
asked May 6, 2016 at 18:38
Ben Davidow
1,2155 gold badges27 silver badges56 bronze badges
3 Answers 3
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)
}
answered May 6, 2016 at 18:51
Chin Leung
15k4 gold badges38 silver badges64 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
)
answered May 6, 2016 at 18:55
Ravinder Reddy
3,8791 gold badge16 silver badges24 bronze badges
Comments
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+1with a count of the values of$Aup to length$m.
Original version:
$result = array_fill(0, $m+1, 0);
foreach($A as $i) {
if(isset($result[$i])) {
$result[$i]++;
}
}
- Create a
$resultarray of zeros with length$m+1 - Loop array
$Aand increment$resultindex of$Avalue
Obviously if you want a function just wrap code in:
function counting($A, $m) {
//code
return $result;
}
answered May 6, 2016 at 19:03
AbraCadaver
79.2k7 gold badges75 silver badges91 bronze badges
Comments
lang-php
array_count_valuescan help