-5

what the PHP function to add numbers together? Like:

echo function("43534");

The output will be: 19 (4+3+5+3+4)

Luc4s
  • 19
  • 5

2 Answers2

1

There is not internal PHP function for this. You can do this using str_split and array_sum methods.

function add($string)
{
    return array_sum(str_split($string));
}

And call:

echo add("43534");

Of curse you need to do some validations.

Piotr Olaszewski
  • 6,017
  • 5
  • 38
  • 65
1

You need a very basic algorithm for this:

  1. Explode by some character
    *You may sometimes need to add numbers bigger than 9. In that case, you have to explode by some character(let's say, a '+' sign), instead of only exploding by every character.
  2. Get integer value of every substring
  3. Add them to the sum
  4. Return the result

Here is your function:

<?php

function add_numbers($string){
    $result = 0;
    $num_array = explode("+", $string);

    foreach($num_array as $num_array_element){
        $result += intval($num_array_element);
    }

    return $result;
}

echo add_numbers("4+3+5+3+4"); // this prints 19

?>
halfer
  • 19,824
  • 17
  • 99
  • 186
WinterChild
  • 969
  • 10
  • 13