How can PHP be used to find duplicate characters in a string?
To find duplicate characters in a string using PHP, we can iterate through each character in the string and keep track of how many times each character appears. If a character appears more than once, we can consider it a duplicate. We can store the duplicate characters in an array and return them at the end.
function findDuplicateCharacters($str) {
$charCount = [];
$duplicates = [];
for ($i = 0; $i < strlen($str); $i++) {
$char = $str[$i];
if (isset($charCount[$char])) {
$charCount[$char]++;
} else {
$charCount[$char] = 1;
}
if ($charCount[$char] > 1 && !in_array($char, $duplicates)) {
$duplicates[] = $char;
}
}
return $duplicates;
}
$string = "hello";
$duplicates = findDuplicateCharacters($string);
print_r($duplicates);