Mohammed H
Mohammed H

Reputation: 7048

what is the efficient method to check an array contains duplicate values in php?

what is the efficient method to check an array contains duplicate values? I have an array which contains emails. I want to know whether there is any email-id repeating.

Update: I am not interested in the repeating values. I want to know whether "It contains duplicate value" or "It doesn't contain duplicate value".

Upvotes: 1

Views: 785

Answers (5)

MIIB
MIIB

Reputation: 1849

This is how i extract duplicate values from an array

  <?php
function array_not_unique( $a = array() )
{
  return array_diff_key( $a , array_unique( $a ) );
}
?>

It returns the duplicate entries. It's the most simple and efficient way.

As you edited your post, the most efficient way to only know that it has duplicate or not is the way that most suggest.

count(array_unique($array)) == count($array)

Upvotes: 1

Shridhar
Shridhar

Reputation: 166

If any one want case insensitive array unique value then try below

function array_iunique($array) {

return array_intersect_key($array,array_unique(
                array_map('strtolower',$array) ) );
}

$array[1] = "[email protected]";
$array[2] = "[email protected]";
$array[3] = "[email protected]";
$array[4] = "[email protected]";

//print_r(array_unique($array));

print_r(array_iunique($array));

// result Array ( [1] => [email protected] [2] => [email protected] )

Upvotes: 1

Mohit Mehta
Mohit Mehta

Reputation: 1285

You should use array_count_values() method to find number of occurrence of elements. It's easy and efficient method.

$array = array('a', 'o', 'p', 'b', 'a', 'p', 'k', 'k', 'k');

print_r(array_count_values($array));

output

Array
(
   [a] => 2
   [o] => 1
   [p] => 2
   etc...
)

Upvotes: 0

ajshort
ajshort

Reputation: 3764

A simple way that should be quite efficient is to make the array unique, and then compare it to the original array to see if any elements have been removed:

count(array_unique($emails)) == count($emails)

Upvotes: 1

William Buttlicker
William Buttlicker

Reputation: 6000

Try this:

if (count(array_unique($arr)) == count($arr)) 
  echo "Array does not contain duplicate elements"; 
else
  echo "Array contains duplicate elements";

Upvotes: 3

Related Questions