Home >Backend Development >PHP Tutorial >How Can I Efficiently Count Unique Values in a PHP Array?

How Can I Efficiently Count Unique Values in a PHP Array?

Susan Sarandon
Susan SarandonOriginal
2024-12-04 00:29:10649browse

How Can I Efficiently Count Unique Values in a PHP Array?

Detecting and Counting Unique Values in an Array

When working with a one-dimensional array, it is often useful to identify and count the occurrences of unique values. To accomplish this, PHP provides the powerful array_count_values() function.

Using array_count_values()

To utilize array_count_values(), simply pass the array to the function like so:

$result = array_count_values($array);

The function will return an associative array where the keys are the unique values from the input array and the corresponding values are the counts of each value's occurrence.

Example

Consider the example array:

$array = ['apple', 'orange', 'pear', 'banana', 'apple', 'pear', 'kiwi', 'kiwi', 'kiwi'];

When we execute:

$result = array_count_values($array);
print_r($result);

The output will be:

Array
(
   [apple] => 2
   [orange] => 1
   [pear] => 2
   [banana] => 1
   [kiwi] => 3
)

This output clearly indicates the counts of each unique value in the original array.

The above is the detailed content of How Can I Efficiently Count Unique Values in a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn