Duplicate words in PHP [on hold]

29
January 12, 2019, at 11:00 AM

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'
Answer 1
$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
Answer 2

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
READ ALSO
Find all child nodes of a parent in tree [on hold]

Find all child nodes of a parent in tree [on hold]

I have a tree in which i want all the left side child and right side child separately in table list but i couldn't get

46
Cannot redeclare class Excel error in Codeigniter / PHPExcel

Cannot redeclare class Excel error in Codeigniter / PHPExcel

I want to export some data in an Excel file, I got This error

43
Wordpress child theme ajax call for functions doesn&#39;t run

Wordpress child theme ajax call for functions doesn't run

I have a wordpress installation with theme: Escapium and i using its own child themeI have added functions

50