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 Quote Link to comment 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.