0

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.

5
  • 3
    array_count_values() What do you want to do if you catch them? Wrapping it in array_filter() to check for those > 1 or == 1 is probably where I would take it. Commented May 8, 2018 at 15:29
  • see here, maybe of some help. stackoverflow.com/questions/1170807/… Commented May 8, 2018 at 15:30
  • I missed the "I need to throw an exception" part. When throwing it do you need to know which specifically are duplicates, or just a generic exception if any is a duplicate? Commented May 8, 2018 at 15:31
  • The issue with array_count_values() is I can't guarantee that the array will not have null values. That only counts strings and integers. Commented May 8, 2018 at 15:32
  • I do. The logic needs to throw an exception if there is more than one Email value. Commented May 8, 2018 at 15:33

2 Answers 2

1

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()

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

It looks like that just removes the second of the two columns. In this case, that wouldn't help me. The logic I need is just to confirm that there are duplicate columns in order to abort create a response status that there are duplicate Email columns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.