Skip to content
Advertisement

PHP – remove duplicate indexes from array, compared by one of it values

I have a PHP array with indexes, its values can be duplicated. I want to remove all duplicated indexes from this array:

JavaScript

So, Index 1 and 2 with the same title “Title B” are duplicated. Only the one with the higher tstamp should be exists, all older ones with same title should be removed from array:

JavaScript

Hope someone understand me and can help to solve my problem.

Advertisement

Answer

Just create an empty array, loop through your old array and add them to the new array with the key as the title.

JavaScript

Output:

JavaScript

This has the added benefit of being able to select titles easier, for example $new['Title A']. If you want the key indexes to still be numerical, you can use $new = array_values($new); to do so. If you use array_values(), the output matches your expected output exactly.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement