0

I've date in following format.

2019-02-27

I've to find sum of digits in above date. I've exploded the above value like this,

$date = '2019-02-27';
$dateArray = explode('-',$date);

Now date array will be like this:

array:3 [▼
   0 => "2019"
   1 => "01"
   2 => "02"
]

With 2 loops, I can get sum of all digits but if there any much better way or builtin function to do this ?

Any kind of suggestion or help is appreciated.

Sagar Gautam
  • 9,049
  • 6
  • 53
  • 84
  • 1
    `any much better way or builtin function to do this` - Yes the imaginatively named - [array_sum()](http://php.net/manual/en/function.array-sum.php) in your case `$total = array_sum(explode('-',$date));` – ArtisticPhoenix Feb 18 '19 at 02:54
  • @ArtisticPhoenix it will return 2023 as output but output i want is 15 – Sagar Gautam Feb 18 '19 at 02:57
  • `15` makes no sense because that is `19-1-2` not a sum. – ArtisticPhoenix Feb 18 '19 at 03:05
  • It’s not clear. From `2019-02-27` do you want 2 + 0 + 1 + 9 + 0 + 2 + 2 + 7 = 23?? If you could make your example consistent, I think it would help. – Ole V.V. Feb 18 '19 at 10:05

2 Answers2

3

You can use str_split to split the date into separate characters and then array_sum them. array_sum will ignore the - characters which are not valid numbers:

$date = '2019-01-02';
echo array_sum(str_split($date));

Output

15

Note that for your $date string of '2019-02-27' the correct result is 23. 15 is the correct result for '2019-01-02' which is what your var_dump output says was the contents of your $date variable at the time.

Nick
  • 138,499
  • 22
  • 57
  • 95
  • @ArtisticPhoenix well if you're going to pull out the thermonuclear device you may as well use `preg_split('/(?=\d)|-/', $date, -1, PREG_SPLIT_NO_EMPTY)` so the `-` characters don't make it into the array... – Nick Feb 18 '19 at 03:11
  • I actually thought about it, but alas I was too lazy... (o.O)> – ArtisticPhoenix Feb 18 '19 at 03:12
1

With 2 loops, I can get sum of all digits but if there any much better way or builtin function to do this ?

Yes

 $total = array_sum(preg_split('//','2019-03-17'));
 echo $total;

Output

  23

Sandbox

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38