Check If An Array Has Duplicate Values Example in PHP

In this simple tutorial I shall illustrate how to check whether a PHP array has duplicated values. In this simple example we will process an array to detect identical or duplicate values. If you want to detect duplicate values within arrays using PHP you can follow this straight-forward example.

How to Check If A PHP Array Has Duplicate Values

In order to achieve this, we will use php’s count function in conjunction with the array_unique function. Together, these tools shall detect duplicate values in PHP arrays.

Let us now explore this with help of the following code snippet.

EXAMPLE CODE

<?php
      $input = array("a" => "green", "red", "b" => "green", "blue", "red");
      $result = array_unique($input);
      if (count($result) !== count($input)) {
          echo "This Array has duplicate value";
      } else {
    	  echo "This Array does not have duplicate value";
      }
?>

The above code create an array of unique values from the given array. Then we will compare the count of the original array with that of the unique array values. If counts have different values, we will know that the initial array contains duplicate values.

OUTPUT

This Array has duplicate value

Conclusion

In this post we have learned a way to check if an array contains duplicate elements using PHP’s array_unique and count functions.

Leave a Reply