Smart way, We know that array_count_values[]
: Counts all the values of an array
Just like you do an array_count_values[] for a single dimensional array, what do you do for a multi dimensional array.
We do it by turning it to one single dimensional array, then we call our funciton
$input = array[
array['07/11' => '134'],
array['07/11' => '134'],
array['07/11' => '145'],
array['07/11' => '145'],
array['07/12' => '134'],
array['07/12' => '99']
];
$output = [];
foreach [$input as $inner]{
foreach [$inner as $key => $value]{
$output[] = "Date: $key, ID: $value, Count:";
}
}
OUTPUT: as you expect
foreach[array_count_values[$output] as $key => $value] {
echo "$key $value
";
}
/*Date: 07/11, ID: 134, Count: 2
Date: 07/11, ID: 145, Count: 2
Date: 07/12, ID: 135, Count: 1
Date: 07/12, ID: 99, Count: 1*/
[PHP 4, PHP 5, PHP 7, PHP 8]
array_count_values — Counts all the values of an array
Description
array_count_values[array $array
]: array
Parameters
array
The array of values to count
Return Values
Returns an associative array of values from array
as keys and their count as value.
Errors/Exceptions
Throws E_WARNING
for every element which is not string or int.
Examples
Example #1 array_count_values[] example
The above example will output:
Array [ [1] => 2 [hello] => 2 [world] => 1 ]
See Also
- count[] - Counts all elements in an array or in a Countable object
- array_unique[] - Removes duplicate values from an array
- array_values[] - Return all the values of an array
- count_chars[] - Return information about characters used in a string
sergolucky96 at gmail dot com ¶
4 years ago
Simple way to find number of items with specific values in multidimensional array:
szczepan.krolgmail.c0m ¶
12 years ago
Here is a Version with one or more arrays, which have similar values in it:
Use $lower=true/false to ignore/set case Sensitiv.
anvil_sa at NOSPAMNO dot hotmail dot com ¶
2 years ago
Based on sergolucky96 suggestion
Simple way to find number of items with specific *boolean* values in multidimensional array:
Dominic Vonk ¶
8 years ago
The case-insensitive version:
rabies dot dostojevski at gmail dot com ¶
15 years ago
I couldn't find a function for counting the values with case-insensitive matching, so I wrote a quick and dirty solution myself:
This prints:
Array
[
[J. Karjalainen] => 3
[60] => 2
[j. karjalainen] => 1
[Fastway] => 2
[FASTWAY] => 1
[fastway] => 1
[YUP] => 1
]
Array
[
[J. Karjalainen] => 4
[60] => 2
[Fastway] => 4
[YUP] => 1
]
I don't know how efficient it is, but it seems to work. Needed this function in one of my scripts and thought I would share it.
pmarcIatIgeneticsImedIharvardIedu ¶
19 years ago
array_count_values function does not work on multidimentional arrays.
If $score[][] is a bidimentional array, the command
"array_count_values [$score]" return the error message "Warning: Can only count STRING and INTEGER values!".