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.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With