This is an interview question:
What is the best way to return the first repeated element out of the array of integers?
Example:
Given an array [12, 46, 244, 0, 12, 83, 48, 98, 233, 83, 26, 91, 119, 148, 98]
.
The return value in this case is 12
.
How can this be done?
CodePad.
You could use
array_unique
to remove all the duplicate values, then iterate over the original and resulting arrays and return the first value that doesn't appear in the resulting array. Something like this:Working demo: http://codepad.org/atFMrhLW.