Skip to content
Advertisement

how display the number of occurrences of each letter in this string

I have an exercise I don’t know how to solve, because I am a beginner in php, here is the exercise summary: the "str_split" function allows you to convert a character string into an array (if we have a $s string that we want to store in a $tab array, we will write "$ tab = str_split ($ s);". using this function, create a function which takes as parameter a character string and display the number of occurrences of each letter in this string.

<html>
    
   <head>
      <title>order</title>
   </head>
   
   <body>
   
      <?php
         function stringFunction($s) {

          $tab = array();
          $counter = 0;
          $tab = str_split($s);
          $count = count($tab);

            for ($i = 0; $i < $count; $i++) {
             for ($j = 0; $j < $count; $j++) {
              if($tab[$i]==$tab[$j]){
                $counter = $counter + 1;
              }
              }
             }
             return $counter;
             }
             echo stringFunction("aakkaaaall");
      ?>
   </body>
</html>

Advertisement

Answer

Something like below should work?

<?php
function stringFunction($s) {

          $tab = array();
          $tab = str_split($s);
          $occurrences = array_fill(0, 26, 0);
          for ($i = 0; $i < count($tab); $i++) {
            $occurrences[(ord($tab[$i])-ord('a'))]++;
        }
        for ($i = 0; $i < count($occurrences); $i++) {
            if($occurrences[$i] != 0) {
                echo(chr(ord('a')+$i) . " = " . $occurrences[$i]."n");
            } 
          }
        }
             echo stringFunction("aajib");
?>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement