Home > Backend Development > PHP Tutorial > How Can I Efficiently Count Duplicate Occurrences in an Array?

How Can I Efficiently Count Duplicate Occurrences in an Array?

Mary-Kate Olsen
Release: 2024-10-27 04:39:02
Original
631 people have browsed it

How Can I Efficiently Count Duplicate Occurrences in an Array?

Counting Duplicate Occurrences in Arrays

In programming, it can be useful to count the number of times duplicate elements appear in an array. To do this, we need to create an efficient solution that accurately captures the desired data.

Understanding the Original Code

The provided code attempts to achieve this by iterating through the array multiple times and maintaining a $previous array to store unique elements and their occurrences. However, it has several issues:

  • The nested loops lead to unnecessary iterations and decreased performance.
  • The logic for determining whether an element is unique or duplicate is flawed.
  • It doesn't correctly update or remove elements from the $previous array.

An Efficient Solution

A simpler and more efficient solution is to use the built-in array_count_values function, which counts the occurrences of each unique element in an array. This function returns an associative array where the keys are the unique elements and the values are their respective counts.

$array = [12, 43, 66, 21, 56, 43, 43, 78, 78, 100, 43, 43, 43, 21];
$vals = array_count_values($array);
Copy after login

This code snippet stores the count of each unique element in the $vals array. The output is:

No. of NON Duplicate Items: 7

Array
(
    [12] => 1
    [43] => 6
    [66] => 1
    [21] => 2
    [56] => 1
    [78] => 2
    [100] => 1
)
Copy after login

This result provides both the number of unique items (7) and the counts for each unique element, which is the desired outcome.

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