PHPCore
PHPCore

Reputation: 121

Replace duplicate words in array (not remove)

I have an array that have multiple set of words, some of them might be duplicated, and i want to replace the duplicated words from array with word: duplicate, and also keep one original. So if i have 5 duplicates, i want 4 of them to be replaced with duplicate and keep original one

$my_array = (0=>'test', 1=>'test2',2=>'test3',3=>'test');

As you see in my array, the array keys 0 and 3 has same value, i want to replace the last value with word 'duplicate'

$my_array = (0=>'test', 1=>'test2',2=>'test3',3=>'duplicate');

I tried different methods but without success:(

Upvotes: 0

Views: 81

Answers (2)

Adam
Adam

Reputation: 3128

Here's one way to do it:

<?php

$my_array = array(0=>'a', 1=>'a',2=>'b',3=>'c');

print_r($my_array);

$my_array2 = array_unique($my_array);

foreach($my_array as $key => $value) {
    if (!array_key_exists($key, $my_array2)) {
        $my_array[$key] = 'duplicate';
    }
}

print_r($my_array);

Upvotes: 1

Alfred Huang
Alfred Huang

Reputation: 18235

Try this, just remember what values you have visited.

$visited = array();
foreach($my_array as $key=>$val) {
    if(isset($visited[$val])) {
        $my_array[$key] = 'duplicate';
    } else {
        $visited[$val] = true;
    }
}

Upvotes: 0

Related Questions