-2

I wanted to know if there is a way that wee can first separate the value of a variable that is an integer and then add or subtract the individual values?

for example:

$a = 24;

2 + 4 = 6

Saman22
  • 21
  • 1
  • Your question has already been answered here:https://stackoverflow.com/questions/3232511/get-the-sum-of-digits-in-php – jspit Nov 25 '20 at 07:41
  • 6
    Does this answer your question? [Get the sum of digits in PHP](https://stackoverflow.com/questions/3232511/get-the-sum-of-digits-in-php) – jspit Nov 25 '20 at 07:43

2 Answers2

0

You mean something like this,

$a = 24;
var_dump(SumEachDigits($a)); // 6

function SumEachDigits(int $int) {
    $intDigitsArr = str_split(strval($int), 1);

    return array_reduce(
        $intDigitsArr, 
        function($acc, $val) { return $acc + intval($val); },
        0
    );
}
ezio4df
  • 3,541
  • 6
  • 16
  • 31
0

You can use str_split() function

<?php

$a = 24;
$array = str_split($a); // return Array ( [0] => 2 [1] => 4 )
$sum = $array[0] + $array[1];

echo $sum; //return 6
Burhan Kashour
  • 674
  • 5
  • 15