Backend Development 4 min read

Detecting Duplicate Elements in an Array with PHP

This article explains how to determine whether an integer array contains duplicate values by iterating through the elements, using a PHP associative array for constant‑time lookups, and provides the full solution code along with its execution flow, time and space complexity analysis.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Detecting Duplicate Elements in an Array with PHP

Given an integer array nums , the task is to return true if any value appears at least twice; otherwise return false .

Below is the PHP implementation. The class Solution defines the method containsDuplicate($nums) , which uses an associative array $map to record elements that have been seen.

class Solution {

    /**
     * @param Integer[] $nums
     * @return Boolean
     */
    function containsDuplicate($nums) {
        $map = array();
        foreach ($nums as $n => $i) {
            if (array_key_exists($i, $map)) {
                return true;
            }
            $map[$i] = $n;
        }
        return false;
    }
}

Function execution flow:

Initialize an empty associative array $map to store elements and their indices.

Iterate over each element in $nums .

For each element, check whether it already exists in $map . If it does, a duplicate is found and the function returns true .

If the element is not present, add it to $map with its index for future checks.

After processing the entire array without finding duplicates, return false .

The algorithm runs in O(n) time, where n is the number of elements in the input array, because each element is examined exactly once.

The space complexity is also O(n) , as the associative array may store up to n unique elements in the worst case.

In conclusion, the optimized PHP solution leverages an associative array for constant‑time lookups, enabling fast and reliable detection of duplicate elements while maintaining linear time and space performance.

algorithmPHParrayDuplicate DetectionTime ComplexitySpace Complexity
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.