Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the sum of alphabetical characters in a string

Tags:

arrays

php

I want to get the sum of all selected values from an array. If a user searches for a word it should return a sum for the searched word. Example below.

$chars = array(1 => 'a', 2 => 'b', 3 => 'c'); // Chars start from a-z
$data = 'aac'; // for example

foreach ($chars as $results) {
    if (strpos($results, $data) !== false) {
         $search = array_search($results, $chars);
    }
}

If search is "aac" then the results should be 1 + 1 + 3 = 5.

I have tried the array_keys() function and it did not work.

like image 695
Tladi Ramahata Avatar asked Dec 17 '25 16:12

Tladi Ramahata


2 Answers

You can split your $data into an array and loop over every character in the string. Search for the string in the array, and if it exists, then add the index you get from array_search() to a $sum variable.

$sum = 0;
foreach (str_split($data) as $char) {
    if (($index = array_search($char, $chars)) !== false) {
        $sum += $index;
    }
}
echo $sum;
  • Live demo at https://3v4l.org/XCK8r
like image 82
Qirel Avatar answered Dec 20 '25 06:12

Qirel


You can use str_split to create a character array, then accumulate lowercase alphabetical characters only into a sum. Use ord to get an ASCII code per letter instead of hardcoding a literal array (the array would only be useful if you want arbitrary weights per character; see other answers).

<?php
$data = "aac";

$result = array_reduce(str_split($data), function ($a, $e) {    
    return $a + (ctype_lower($e) ? ord($e) - 96 : 0);
}, 0);

echo $result; // => 5

If you wish to ignore case and treat "A" as "a", you can use strtolower.

<?php
$data = "aAc";

$result = array_reduce(str_split(strtolower($data)), function ($a, $e) {    
    return $a + (ctype_lower($e) ? ord($e) - 96 : 0);
}, 0);

echo $result; // => 5
like image 39
ggorlen Avatar answered Dec 20 '25 08:12

ggorlen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!