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
Release: 2024-12-04 00:29:10
Original
594 people have browsed it

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);
Copy after login

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'];
Copy after login

When we execute:

$result = array_count_values($array);
print_r($result);
Copy after login

The output will be:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template