How to use Associative Array In PHP
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
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