April 18, 2012
How to get SQL-like HAVING and GROUP BY for PHP arrays?
Question by Average Joe
Is there a PHP code snippet or a built in array function that would do kind of like what a sql statement with having and group by does? That is removing the dups and counting the occurrences and giving you back an array that you can use for reporting/debugging purposes.
An example may clarify;
say your array is like this
Array (
['0'] => usa
['1'] => minnesota
['2'] => california
['3'] => san fransisco
['4'] => los angeles
['5'] => san fransisco
['6'] => malibu
['7'] => malibu
['8'] => malibu
['9'] => usa
}
and you want something back like this, or something to this effect..
Array (
['usa'] => 2
['minnesota'] => 1
['california'] => 1
['san fransisco'] => 2
['los angeles'] => 1
['malibu'] => 3
}
Answer by David Z.
http://www.php.net/manual/en/function.array-count-values.php
You can use the following code to do this:
array_count_values ($myArray)
Answer by Starx
Use array_count_values()
to get the number of duplicates
$array = array(...);
$duplicate = array_count_values($array);