Matt Larsuma
Matt Larsuma

Reputation: 1519

PHP - Check for duplicate values in an associative array

I have an associative array of headers and I need to throw an exception if there are duplicate values:

Array
(
    [0] => Email
    [1] => Name
    [2] => Something
    [3] => Else
    [4] => Email
)

What's the best way to catch that there are two or more Email values? array_values is not getting the values. I don't want array_unique, as I want to abort if there are multiples.

Upvotes: 0

Views: 1626

Answers (2)

FULL STACK DEV
FULL STACK DEV

Reputation: 15951

If you want to do it in a Laravel way you can use Collection

collect($yourArray)->unique(); // will return the collection of unique values.

Hope this helps

Upvotes: 0

Eddie
Eddie

Reputation: 26844

One option to check if an array has duplicates is to get the count of unique values. If it does not match the count of the original array, then there are duplicates.

$arr = array('Email','Name','Something','Else','Email');

if ( count( $arr ) !== count( array_unique( $arr ) ) ) echo "Some duplicates";

Doc: array_unique()

Upvotes: 1

Related Questions