Find first number of each element in array and add them up without using strings

Viewed 56
   public function pom() {
        $array = [25, 12, 5, 82, 15];
        $result = 0;
        for($i = 0; $i < count($array); $i++) {
            $first = str_split($array[$i]);
            if(is_numeric($first[0])) 
            $result += $first[0];
        }
        return $result;
    }

it works like this but question says i cannot use strings . Does it mean i cannot use str_split ?

2 Answers

You can do that with substr array_map() and array_sum(),

<?php
$array = [25, 12, 5, 82, 15];
function sum_first_digit($array) {
   $sum = array_sum(array_map(function ($a){return 
substr($a,0,1);}, $array));
   return $sum;
 }
 echo sum_first_digit($array);
?>

Output: 17

Extracting the first digit without the use of a string function means in my opinion only using calculations. Example:

$n = 781234;
$result = intdiv($n,pow(10,floor(log10($n)))); // 7
Related