0

I have the following code on PERL:

$Mid = 123;
$csum=0;
$csum+=$_ foreach split //,$Mid;
$csum%=10;

It calculates $csum based on $Mid which is a number

How to do the same on PHP?

stckvrw
  • 1,689
  • 18
  • 42
  • What have you tried? "php sum digits in number" yields a lot of results on google/stackoverflow ([this question](https://stackoverflow.com/questions/3232511/get-the-sum-of-digits-in-php) for instance) – Dada Oct 08 '19 at 07:47

1 Answers1

1

The following should do the trick:

$mid = 123;
$csum = 0;

foreach(str_split($mid) as $m){ // Loop $mid by character
  $csum+= $m;                   // Add current $character ($m) to our $csum
}

$csum = $csum % 10;             // Modulo by 10
echo $csum; // 6

Working PHP, and to compare, the working Perl version

Brett Gregson
  • 5,867
  • 3
  • 42
  • 60
  • [`array_sum`](http://php.net/array_sum) | [`%=`](http://php.net/language.operators.assignment) – daxim Oct 08 '19 at 08:05