Home  >  Article  >  Backend Development  >  How Can I Efficiently Count Duplicate Items in an Array?

How Can I Efficiently Count Duplicate Items in an Array?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 18:46:30987browse

How Can I Efficiently Count Duplicate Items in an Array?

Counting Duplicate Items in Arrays: A Refined Approach

In programming, often we need to identify and count duplicate elements within an array. While custom loops can be employed for this purpose, leveraging built-in functions offers a simpler and more efficient solution.

Consider the following code:

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

$vals = array_count_values($array);</code>

The array_count_values function takes an array as an argument and returns a new array with the frequencies of each unique element. This simplifies counting duplicates and retrieving non-duplicate items with their respective occurrences.

The resulting array is:

<code class="php">Array
(
    [12] => 1
    [43] => 6
    [66] => 1
    [21] => 2
    [56] => 1
    [78] => 2
    [100] => 1
)</code>

This array clearly shows the number of occurrences of each unique element in the original array. By keeping track of both unique and duplicate elements, we can effectively analyze and manipulate array data.

The above is the detailed content of How Can I Efficiently Count Duplicate Items in an 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