I have an array, $arrayName = array(1,2,1,3,4,3,2,5);
. I want the result as:
Array (
[1] => 2
[2] => 2
[3] => 2
[4] => 1
[5] => 1
)
Without using array_count_values()
, what is the logic behind array_count_values()
?
This method will only loop each value once compared to other methods posted here.
Instead of looping the full array I get unique values and count them with array_keys and count.
$arrayName = array(1,2,1,3,4,3,2,5);
$values = array_unique($arrayName);
Foreach($values as $val){
$count[$val] = count(array_keys($arrayName, $val));
}
Var_dump($count);
In your example I think my method may actually be slower than looping the full array, but if this was a large array there may be a benefit of not looping the full array.
The best solution is to use array_count_values function. That counts frequency of values in an array. See this - http://php.net/manual/en/function.array-count-values.php
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
However, If you don't want to use that function, you can do an ugly way of for loop.
$arrayName = array(1,2,1,3,4,3,2,5);
$resultArray = array();
foreach($arrayName as $value) {
$resultArray[$value] = isset($resultArray[$value]) ? $resultArray[$value] + 1 : 1;
}
print_r($resultArray); // Array ( [1] => 2 [2] => 2 [3] => 2 [4] => 1 [5] => 1 )