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.

Matt Larsuma
  • 1,456
  • 4
  • 20
  • 52
  • 3
    [`array_count_values()`](http://php.net/manual/en/function.array-count-values.php) 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. – Michael Berkowski May 08 '18 at 15:29
  • see here, maybe of some help. https://stackoverflow.com/questions/1170807/how-to-detect-duplicate-values-in-php-array – Yeeooow May 08 '18 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? – Michael Berkowski May 08 '18 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. – Matt Larsuma May 08 '18 at 15:32
  • I do. The logic needs to throw an exception if there is more than one Email value. – Matt Larsuma May 08 '18 at 15:33

2 Answers2

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

Eddie
  • 26,593
  • 6
  • 36
  • 58
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

FULL STACK DEV
  • 15,207
  • 5
  • 46
  • 66
  • 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. – Matt Larsuma May 08 '18 at 16:20