Search code examples
phparrayssummappingcpu-word

Get consecutive letters, translate each letter to a number, and sum numbers in group


Let's say I have these two related arrays:

$letters = ['a', 'b', 'c', 'd', 'e'];
$replace = [1, 5, 10, 15, 20];

And a string of letters separated by spaces.

$text = "abd cde dee ae d";

I want to convert consecutive letters to their respective numbers, sum the numbers, then replace the original letters with the total.

Using str_replace() isn't right because the values are compressed as a string before I can sum them.

$re = str_replace($letters, $replace, $text);
echo $re;  //this output:
   
1515 101520 152020 120 15

I actually want to sum the above numbers for each "word" and the result should be:

21 45 55 21 15

What I tried:

$resultArray = explode(" ", $re); 

echo array_sum($resultArray).'<br />';

It incorrectly outputs:

255190

EDIT:

My actual data contains arabic multibyte characters.

$letters = array('ا', 'ب','ج','د' ) ;
$replace = array(1, 5, 10, 15 ) ;
$text = "جا باب جب"; 

Solution

  • Convert the string into an array and use array_sum.

    array_sum(explode(' ', $re));
    

    Edit

    Sorry, misunderstood:

    $letters = array('a','b','c', 'd', 'e');
    
    $replace = array( 1,  5,  10, 15 , 20);
    
    $text = "abd cde dee ae d" ;
    
    $new_array = explode(' ', $text);
    
    $sum_array = array();
    
    foreach ($new_array as $string)
    {
    
      $nums = str_split($string);
    
      foreach ($nums as &$num)
      {
        $num = str_replace($letters, $replace, $num);
      }
    
      $sum_array[] = array_sum($nums);
    
    }
    
    echo implode(' ', $sum_array);