laketuna
laketuna

Reputation: 4080

Simple way to identify repeated strings in an array? (PHP)

I have an array with values $somearray = array('car','bike','legs,'car'). I'd like to find out which of these values in $somearray are repeated and pick out the index. In this example the answer would be 'car' and the index of the array would be 0 and 3.

I'm wondering if this can be done simply in a few lines, perhaps using some PHP function that I don't know, or do I need to explicitly make comparison in nested loops?

TIA!

Upvotes: 1

Views: 910

Answers (2)

steve
steve

Reputation: 576

There's a good answer on this similar question - How to detect duplicate values in PHP array?

To get the array indexes, I would then filter any array value > 1 and get the indexes

Upvotes: 0

zerkms
zerkms

Reputation: 254926

The solution is pretty simple and I bet you can write it yourself. All you need is just 2 functions: array_count_values() and array_keys() with specified second argument (thanks to @prodigitalson)

Upvotes: 3

Related Questions