Is there a way in php to count how often a value exists in a large array? So if I have an array like this:
$array = "1,2,3,4,joe,1,2,3,joe,joe,4,5,1,6,7,8,9,joe";
is there a way to output a new array that tells me (and sorts) which is used most and how many for each? $result = array(
[joe] => 4
[1] => 3
[2] =>2
etc...
)
I've seen the php array_count_values, but can this be sorted by most -> least? or is there an easier way? Thanks everyone! (PHP 4, PHP 5, PHP 7, PHP 8) array_count_values — Counts all the values of an array Descriptionarray_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
<?php $array = array(1, "hello", 1, "world", "hello"); print_r(array_count_values($array)); ?>
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:
<?php
$list
= [ ['id' => 1, 'userId' => 5], ['id' => 2, 'userId' => 5], ['id' => 3, 'userId' => 6], ]; $userId = 5;echo array_count_values(array_column($list, 'userId'))[$userId]; // outputs: 2 ?>
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.
<?php
$ar1
[] = array("red","green","yellow","blue");
$ar1[] = array("green","yellow","brown","red","white","yellow");
$ar1[] = array("red","green","brown","blue","black","yellow");
#$ar1= array("red","green","brown","blue","black","red","green"); // Possible with one or multiple Array
$res = array_icount_values ($ar1);
print_r($res);
function array_icount_values($arr,$lower=true) {
$arr2=array();
if(!is_array($arr['0'])){$arr=array($arr);}
foreach($arr as $k=> $v){
foreach($v as $v2){
if($lower==true) {$v2=strtolower($v2);}
if(!isset($arr2[$v2])){
$arr2[$v2]=1;
}else{
$arr2[$v2]++;
}
}
}
return $arr2;
}
/*
Will print:
Array
(
[red] => 3
[green] => 3
[yellow] => 4
[blue] => 2
[brown] => 2
[white] => 1
[black] => 1
)
*/
?>
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:
<?php
$list
= [ ['id' => 1, 'result' => true], ['id' => 2, 'result' => true], ['id' => 3, 'result' => false], ]; $result = true;echo array_count_values(array_map(function($v) {return $v?'true':'false';},array_column($list, 'result')))[$result] // outputs: 2?>
Dominic Vonk ¶ 8 years
ago
The case-insensitive version:
<?php function array_count_values_ci($array) { $newArray = array(); foreach ($array as $values) { if (!array_key_exists(strtolower($values), $newArray)) { $newArray[strtolower($values)] = 0; } $newArray[strtolower($values)] += 1; } return $newArray; } ?>
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:
<pre><?php function array_icount_values($array) { $ret_array = array(); foreach($array as $value) { foreach($ret_array as $key2 => $value2) { if(strtolower($key2) == strtolower($value)) { $ret_array[$key2]++; continue 2; } } $ret_array[$value] = 1; } return $ret_array; }$ar = array('J. Karjalainen', 'J. Karjalainen', 60, '60', 'J. Karjalainen', 'j. karjalainen', 'Fastway', 'FASTWAY', 'Fastway', 'fastway', 'YUP'); $ar2 = array_count_values($ar); // Normal matching $ar = array_icount_values($ar); // Case-insensitive matching print_r($ar2); print_r($ar); ?></pre>
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!".
How do you count occurrences of each element in an array in PHP?
array_count_values() function in PHP
The array_count_values() function returns an array with the number of occurrences for each value. It returns an associative array. The returned array has keys as the array's values, whereas values as the count of the passed values.
How do you find the frequency of a value in an array?
Algorithm. Declare and initialize an array arr.. Declare another array fr with the same size of array arr. ... . Variable visited will be initialized with the value -1. ... . The frequency of an element can be counted using two loops. ... . Initialize count to 1 in the first loop to maintain a count of each element..
What is the use of array_count_values () in PHP explain with example?
The array_count_values() function is used to count all the values inside an array. In other words, we can say that array_count_values() function is used to calculate the frequency of all of the elements of an array. Parameters: This function accepts a single parameter $array.
How do you count the number of repeated values in an array?
#include <stdio.h>. int main(). //Initialize array.. int arr[] = {1, 2, 3, 4, 2, 7, 8, 8, 3};. //Calculate length of array arr.. int length = sizeof(arr)/sizeof(arr[0]);. printf("Duplicate elements in given array: \n");.
|