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
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
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
);
}
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