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

Asked

Viewed 94 times

1

$numero = 15;
echo "Resultado: $numero";

2 answers

5


Combine array_sum with str_split and save code - ideone example

array_sum - Compute the sum of the elements of an array

str_split - Convert 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 one being with tamanho length, otherwise each piece 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: see in ideone

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

for ($i=0;$i<count($num);$i++){
    $result += $num[$i];
}
  • Putz! I forgot the array_sum! Very good!

  • Very good tbm! Thanks @leo Caracciolo

1

Use the str_split to separate the digits and then add them up:

$numero = 15;
$num = str_split($numero, 1);
echo $num[0] + $num[1];
  • Very good @Andreicoelho! vlww

  • @Quiet jsdev... Try to make the question a little clearer. This avoids future negativities!

  • @Jsdev read this when you have time: https://answall.com/help/how-to-ask Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.