-4

I have probably information about whether it is available in PHP to detect a duplicate and a book about not removing it and adding it to -1, -2, -3

Example:

$string = 'H4,H4,H3,WY21W,W5W,W5W,WY21W,W21/5W,W21/5W,W21W,W16W,W5W';

Result:

$output = 'H4,H4-1,H3,WY21W,W5W,W5W-1,WY21W-1,W21/5W,W21/5W-1,W21W,W16W,W5W-2'
danko12
  • 79
  • 8
  • Yes you can do that, but what have you tried so far? – ArtOsi Jan 11 '19 at 08:11
  • Possible duplicate of [How do I check if a string contains a specific word?](https://stackoverflow.com/questions/4366730/how-do-i-check-if-a-string-contains-a-specific-word) – Sir Catzilla Jan 11 '19 at 08:11
  • @Miaan - IMO that question indeed looks the same, but the answer does not fit in the scope of this question. This question is also about adding some data after the words. – Koen Hollander Jan 11 '19 at 08:13
  • I was looking for such an example, however, I can not find. I just wrote that it removes duplicate values. – danko12 Jan 11 '19 at 08:19
  • @Danko12 - Please don't forget to mention everything you did, so we don't repeat those steps – Koen Hollander Jan 11 '19 at 08:21
  • Possible duplicate of [php: rename duplicate keys by giving number in foreach](https://stackoverflow.com/questions/23540944/php-rename-duplicate-keys-by-giving-number-in-foreach) – Koen Hollander Jan 11 '19 at 08:24

2 Answers2

2
$string = 'H4,H4,H3,WY21W,W5W,W5W,WY21W,W21/5W,W21/5W,W21W,W16W,W5W';
$parts = explode(',', $string); // split by comma
$used = []; // array to count the number of occurrences
$result = []; // array to take the "new" elements

foreach($parts as $part) {
  if(isset($used[$part])) { // if there is an entry in the counter array already,
                            // increment it by one,
    $used[$part]++;
  }
  else {                    // else initialize with 0
    $used[$part] = 0;
  }
  // put part into new array, append -(counter) if counter > 0
  $result[] = $part . ($used[$part] ? '-'.$used[$part] : '');
}

echo implode(',', $result); // join together with comma
misorude
  • 3,381
  • 2
  • 9
  • 16
1

Pretty much the same as misorude's answer.

<?php

$string = 'H4,H4,H3,WY21W,W5W,W5W,WY21W,W21/5W,W21/5W,W21W,W16W,W5W';
$values  = explode(',', $string);

foreach($values as $k => $value)
    if($counts[$value] = !isset($counts[$value]) ? 0 : $counts[$value]-1)
        $values[$k] = $value . $counts[$value];

print implode(',', $values);

Output:

H4,H4-1,H3,WY21W,W5W,W5W-1,WY21W-1,W21/5W,W21/5W-1,W21W,W16W,W5W-2
Progrock
  • 7,373
  • 1
  • 19
  • 25