How to Count Duplicate Elements in a PHP Array?

DDD
Release: 2024-10-27 00:23:03
Original
425 people have browsed it

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

Result:

Number of Unique 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() 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!

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
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!