Backend Development 4 min read

PHP Solution for Detecting Duplicate Elements in an Integer Array

This article explains how to determine whether an integer array contains duplicate values by iterating through each element, using a PHP associative array to track occurrences, and returning true if any value appears at least twice, with detailed code, execution flow, and time‑space complexity analysis.

php中文网 Courses
php中文网 Courses
php中文网 Courses
PHP Solution for Detecting Duplicate Elements in an Integer Array

Introduction: Detecting duplicate elements in an array requires traversing each element and checking for repeated occurrences.

Problem: Given an integer array nums , return true if any value appears at least twice; otherwise return false .

Example:

Input: nums = [1,2,3,1]
Output: true

Input: nums = [1,2,3,4]
Output: false

Solution: The PHP class Solution implements containsDuplicate($nums) using an associative array $map to store seen elements. The function iterates over $nums , checks if the current element already exists in $map , returns true on a duplicate, otherwise adds the element to $map . After the loop, it returns false .

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;
    }
}

Execution flow: 1) Initialize an empty associative array $map . 2) For each element in $nums , check if it exists in $map . If found, return true . If not, store the element and its index in $map . 3) If the loop finishes without finding duplicates, return false .

Complexity: Time complexity O(n) where n is the number of elements; space complexity O(n) due to the auxiliary associative array.

Conclusion: The optimized PHP solution leverages an associative array for constant‑time lookups, enabling fast and reliable detection of duplicate elements while maintaining stable performance on large datasets.

PHPDuplicate DetectionTime ComplexitySpace Complexityarray algorithm
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.