How to sum this number? Example: "the number is 15 then it would be 1 + 5 = result" [closed]

1
$numero = 15;
echo "Resultado: $numero";
    
asked by anonymous 13.12.2018 / 22:59

2 answers

5

Combine array_sum with str_split and save code - ideone example

array_sum - Calculates the sum of the elements of an array

str_split - Converts a string to an array. Syntax str_split(string,tamanho) If the optional parameter tamanho is specified, the returned array will be broken into pieces with each being tamanho length, otherwise each chunk will have a length character

$numero=123456789;

echo array_sum(str_split($numero));
  

With this solution you have to write a lot of code

$num = str_split($numero, 1);
echo $num[0] + $num[1] + $num[2] + $num[3] +  $num[4] + .................;
  

In this case it would be better: view on ideone

$result=0;
$numero = 123456789;
$num = str_split($numero, 1);

for ($i=0;$i<count($num);$i++){
    $result += $num[$i];
}
    
13.12.2018 / 23:58
1

Use str_split to separate the digits and then add them:

$numero = 15;
$num = str_split($numero, 1);
echo $num[0] + $num[1];
    
13.12.2018 / 23:02