Get Duplicate Values from an Array in PHP

In this post, we will explore how to identify duplicate values in a PHP array. We’ll provide you with an example of how to retrieve duplicate values from an array in PHP.

Get Duplicate Values from an Array in PHP

You will learn how to locate duplicate values within an array in PHP, Laravel framework.We will make use of the array_unique function and the array_diff_assoc function to fetch duplicate values within a PHP array.

Let’s take a look at the following code snippet that demonstrates how to identify duplicate values within an array using PHP.<h4>EXAMPLE CODE</h4>

<?php
      
  $originalArray = [1, 2, 3, 2, 4, 5, 3];
      
  $duplicateValues = array_diff_assoc($originalArray, array_unique($originalArray));
      
  echo "Duplicate values in the array: ";

  print_r($duplicateValues);
?>

In this example, the $originalArray contains a mix of unique and duplicate values. We utilize the array_unique() function to eliminate the unique values from the array.

Then, the array_diff_assoc() function helps us find the differences between the original array and the array containing only unique values, effectively revealing the duplicate values.

OUTPUT

Duplicate values in the array: 
			Array ( [3] => 2 [6] => 3 )

Conclusion

In this post we have learned how to identify duplicate values in a PHP array using PHP’s array_unique and array_diff_assoc functions.

Leave a Reply