This tutorial will discuss about unique ways to check if all elements in array are unique in php.
Table Of Contents
Method 1: Using array_unique() function
The array_unique()
function in PHP, accepts an array as an argument, and returns a new array without duplicate values.
So, to check if an array $arr
contains only unique elements, pass that array $arr
to the array_unique()
function. It will return a new array $uniqArr
, then compare the size of this new array and the size of original array i.e. $arr
. If the size is equal, then it means both the arrays are equal.
Let’s see the complete example,
Frequently Asked:
<?php $arr = [11, 42, 33, 56, 78, 29]; // Get an array of unique elements $uniqArr = array_unique($arr); // Check if the count of elements in array // and unique array is equal if (count($uniqArr) === count($arr)) { echo "Yes, all elements of array are unique"; } else { echo "No, all elements of array are not unique"; } ?>
Output
Yes, all elements of array are unique
Method 2: Using foreach() and in_array()
Intialize an new array $uniqArr
, it will store unique elements only. Then iterate over all the elements of original array $arr
, and for each element check it exists in the new array $uniqArr
or not. If exists, then mark the result as false and break the loop. If it does not exists in the unique array $uniqArr
, then add it.
At the end of loop if the result is true, then it means array has duplicate values.
Let’s see the complete example,
<?php $arr = [11, 42, 33, 56, 78, 29]; // A new array to store unique elements only $uniqArr = []; $result = true; // Iterate over all elements of array foreach ($arr as $element) { // Check if exist in another array if (in_array($element, $uniqArr)) { $result = false; break; } $uniqArr[] = $element; } if ($result) { echo "Yes, all elements of array are unique"; } else { echo "No, all elements of array are not unique"; } ?>
Output
Yes, all elements of array are unique
Summary
We learned about two ways to check if an array has unique values only in PHP.