I made this code to return the number of occurrences of letters in a string. this function returns ‘6a3b5y’ but I want it to respect the order and display ‘4a3b2a5y’ how to change it to display ‘4a3b2a5y’ ?
function encode($input) { $l = mb_strlen($input, 'UTF-8'); $unique = array(); for($i = 0; $i < $l; $i++) { $char = mb_substr($input, $i, 1, 'UTF-8'); if(!array_key_exists($char, $unique)) $unique[$char] = 0; $unique[$char]++; } $a=[]; foreach($unique as $k=>$val){ $a[]= $val.$k ; } return implode("",$a) ; } echo encode('aaaabbbaayyyyy') ;
Advertisement
Answer
Use a variable to hold the previous character. Compare the current character to it. If they’re the same, increment a counter. If they’re not, output the previous character and counter, then reset the variables.
At the end, output the final character and counter.
function encode($input) { $output = ''; $l = mb_strlen($input, 'UTF-8'); $prevchar = mb_substr($input, 0, 1, 'UTF-8'); $count = 1; for($i = 1; $i < $l; $i++) { $char = mb_substr($input, $i, 1, 'UTF-8'); if ($char == $prevchar) { $count++; } else { $output .= "$count$prevchar"; $count = 1; $prevchar = $char; } } $output .= "$count$prevchar"; return $output; }