PHP Program to Print All Duplicate Characters in a String
Last Updated :
17 Jan, 2024
This article will show you how to print duplicate characters in a string using PHP. Detecting and printing duplicate characters in a string is a common task in programming. In this article, we will explore various approaches to achieve this.
Using array_count_values() Function
The array_count_values() function is used to count the occurrences of each value in an array, simplifying the process.
PHP
<?php
function printDuplicates( $str ) {
$charCount = array_count_values ( str_split ( $str ));
echo "Duplicate characters: " ;
foreach ( $charCount as $char => $count ) {
if ( $count > 1) {
echo "$char " ;
}
}
}
$str = "Welcome to GeeksforGeeks" ;
printDuplicates( $str );
?>
|
Output
Duplicate characters: e o G k s
Using Associative Array
One of the most basic methods is to use an associative array to keep track of the occurrence of each character in the string.
PHP
<?php
function printDuplicates( $str ) {
$charCount = [];
for ( $i = 0; $i < strlen ( $str ); $i ++) {
$char = $str [ $i ];
if (isset( $charCount [ $char ])) {
$charCount [ $char ]++;
} else {
$charCount [ $char ] = 1;
}
}
echo "Duplicate characters: " ;
foreach ( $charCount as $char => $count ) {
if ( $count > 1) {
echo "$char " ;
}
}
}
$str = "Welcome to GeeksforGeeks" ;
printDuplicates( $str );
?>
|
Output
Duplicate characters: e o G k s
Share your thoughts in the comments
Please Login to comment...