Check if Array Contains Duplicates in PHP

This tutorial will discuss about a unique way to check if an array contains duplicates elements in php.

To check if an array contains any duplicate element or not we are going to use the array_unique() function.

The array_unique() function accepts an array as an argument and return a new array containing only unique elements from the given array. Basically the return array will not have any duplicate elements.

So we can pass over our original array to the array_unique() function and compare the size of the returned array with the size of original array. If the size of both the arrays are equal then it means the original array has no duplicate element. Otherwise, if original array has more elements, then it means that the original array has duplicate elements.

Let’s see the complete example,

<?php
$arr = array(23, 89, 16, 11, 21, 89, 90);

// Get a copy of unique elements from array
$uniqArray = array_unique($arr);

// If size of both the array is equal,
// then it means array has no duplicates
if (count($uniqArray) < count($arr)) {
    echo "Yes, the array have some duplicate elements";
} else {
    echo "No, the array does not contain any duplicate element";
}
?>

Output

Yes, the array have some duplicate elements

Summary

We learned a way to check if an array contains duplicate elements in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top