PHP Program to Print All Duplicate Characters in a String
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.
Table of Content
- Using array_count_values() Function
- Using Associative Array
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 )); // Print duplicate characters echo "Duplicate characters: " ; foreach ( $charCount as $char => $count ) { if ( $count > 1) { echo "$char " ; } } } // Driver code $str = "Welcome to w3wiki" ; 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 = []; // Iterate through each character // in the string for ( $i = 0; $i < strlen ( $str ); $i ++) { $char = $str [ $i ]; // Check if the character is already // in the associative array if (isset( $charCount [ $char ])) { $charCount [ $char ]++; } else { $charCount [ $char ] = 1; } } // Print duplicate characters echo "Duplicate characters: " ; foreach ( $charCount as $char => $count ) { if ( $count > 1) { echo "$char " ; } } } // Driver code $str = "Welcome to w3wiki" ; printDuplicates( $str ); ?> |
Output
Duplicate characters: e o G k s
Contact Us