Home >Backend Development >PHP Tutorial >How to Count Duplicate Elements in a PHP Array?

How to Count Duplicate Elements in a PHP Array?

DDD
DDDOriginal
2024-10-27 00:23:03515browse

How to Count Duplicate Elements in a PHP Array?

Counting Occurrences of Duplicates in an Array

In PHP, you can easily count the occurrences of duplicate items in an array using the array_count_values() function. This function returns an associative array where the keys are the unique elements from the original array and the values are the corresponding counts.

To demonstrate its usage, consider the following 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 'Number of Unique Items: ' . count($vals) . '<br><br>';
print_r($vals);</code>

Result:

Number of Unique Items: 7
Array
(
    [12] => 1
    [43] => 6
    [66] => 1
    [21] => 2
    [56] => 1
    [78] => 2
    [100] => 1
)

As you can see, array_count_values() efficiently counts the occurrences of each duplicate item and returns an array of only unique items with their respective occurrences. This approach simplifies the task of identifying and quantifying duplicates within an array without the need for complex iteration and comparisons.

The above is the detailed content of How to Count Duplicate Elements 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