Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace the duplicated values in a string by a specific character?

How can I change the value of the duplicated character in a string?

if they are duplicated I want to have a specific value for that else if they are not, I also want to put a specific value for that too.

Scenario 1:
Input: hello

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output: ..??.

Scenario 2:

Input: elephant
Output: ?.?….

$str = "elephant";

$arr= str_split($str);

    for($i = 0; $i < count($arr); $i++) {  
     for($j = $i + 1; $j < count($arr); $j++) {  
        if($arr[$i] == $arr[$j]){
          
       }
     }  
    }

I really don’t know on how will I change the value of it then implode them again.

>Solution :

try this:

$str = "hello";
$arr = str_split($str);
$duplicates = array_unique(array_diff_assoc($arr,array_unique($arr)));
for($i = 0; $i < strlen($str); $i++) {
   if(in_array($str[$i], $duplicates)) {
      $str[$i] = '?';
   } else {
      $str[$i] = '.';
   }
}
echo $str;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading