0

I have a PHP string that contains numbers. Is there a way to add up all the numbers in a string?

For example: I have a string called $soc_count. That string outputs the following:

1 1

Is there a way to add up all the numbers in a string?

My code:

<?php $soc_count = [];$soc_count = (get_row_layout() == 'irl_today_social_media');?>
<?php echo $soc_count;?>
Gregory Schultz
  • 864
  • 7
  • 24

2 Answers2

3

Assuming numbers are positive integers and string is not empty, you can try this:

eval('$sum = ' . trim(preg_replace('/[^0-9]+/', "+0+", $soc_count), '+') . ';');

echo $sum;
Anatoliy R
  • 1,749
  • 2
  • 14
  • 20
0

Use explode on your string of numbers, and then sum up the array:

$soc_count = "1 1";
$nums = explode(" ", $soc_count);
$total = array_sum($nums);
echo $total;

For a more general solution, which would cover a string of any type having numbers in it, we can try using preg_match_all:

$soc_count = "1 quick brown fox jumped over 1 lazy dog.";
preg_match_all("/\d+/", $soc_count, $matches);
$nums = $matches[0];
$total = array_sum($nums);
echo $total;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360