c_pattle Posted November 19, 2010 Share Posted November 19, 2010 I was wondering if anyone knows a good way to check for an even number of each character in a string. For example if the string is "abbacc" then it will return true as there are two of each character. However if the string is "ababc" it will return false as there is only 1 c. Thanks for any help Link to comment https://forums.phpfreaks.com/topic/219141-check-even-number-of-each-character-in-string/ Share on other sites More sharing options...
JasonLewis Posted November 19, 2010 Share Posted November 19, 2010 You'd need to split the string using str_split. Then loop over each letter and add it to another array, then remove it from that array again if there is another of the same letter. If there is anything in the array at the end, then there were odd leters. Like this: $string = 'abcabc'; $odds = array(); foreach(str_split($string) as $letter){ if(($pos = array_search($letter, $odds)) !== false){ array_splice($odds, $pos, 1); }else{ $odds[] = $letter; } } if(empty($odds)){ echo "String is even."; }else{ echo "String is odd."; } Good luck. Link to comment https://forums.phpfreaks.com/topic/219141-check-even-number-of-each-character-in-string/#findComment-1136414 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.