How Can I Efficiently Count Duplicate Items in an Array in PHP?

Linda Hamilton
Release: 2024-10-26 21:43:29
Original
554 people have browsed it

How Can I Efficiently Count Duplicate Items in an Array in PHP?

Counting Duplicate Items in Arrays Efficiently

In programming, it is often necessary to count the occurrences of duplicate items in an array. One common approach is to use arrays or nested loops to keep track of the counts. However, an alternative solution offers a more concise and efficient method: the array_count_values() function.

To use array_count_values(), simply pass your array as the argument. It will return a new array with the keys as the unique values from the original array and the values as the respective counts.

Consider the following code example:

<code class="php">$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);

$vals = array_count_values($array);

echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>';
print_r($vals);</code>
Copy after login

Output:

No. of NON Duplicate Items: 7
Array
(
    [12] => 1
    [43] => 6
    [66] => 1
    [21] => 2
    [56] => 1
    [78] => 2
    [100] => 1
)
Copy after login

As you can see, array_count_values() provides an easy and elegant solution for counting duplicate items in an array. It returns an array of unique values along with their corresponding counts, eliminating the need for manual loop iterations and array manipulation.

The above is the detailed content of How Can I Efficiently Count Duplicate Items in an Array in PHP?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!