0

I am getting o/p like "11111" and I want to sum all these digits that should become 5. But if I use count count it is showing one only i.e, 1.Rather it should show 5.

Below is my code,

$count = count($inventory['product_id']);

$product_total = $count;
echo $product_total;//o/p => 1.

I need echo $product_total;//o/p => 5.

B. Desai
  • 16,414
  • 5
  • 26
  • 47
Moha kumar
  • 35
  • 1
  • 1
  • 11

4 Answers4

2

You can use the following using str_split to get an array with all characters (in your case digits) and using array_sum to get the sum of all the digits:

$digits = "11112";
$arrDigits = str_split($digits);

echo array_sum($arrDigits); //6 (1 + 1 + 1 + 1 + 2)

Demo: https://ideone.com/tZwi9J

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
0

Count is used for counting array elements.

What you can do in PHP, is to iterate over a string using either a foreach (not 100% sure) or for loop for this and accessing the elements like array elements by their index:

$str = '111111123545';
$sum = 0;
for ($i = 0; $i < strlen($str); $i++) {
    $sum += intval($str[$i]);
}

print $sum; // prints 26

Alternativly, you can split the string using no delimiter and using the array_sum() function on it:

$str = '111111123545';
$sum = array_sum(str_split($str));
print $sum; // prints 26
Manuel Mannhardt
  • 2,191
  • 1
  • 17
  • 23
0
array_sum(str_split($number));
AZinkey
  • 5,209
  • 5
  • 28
  • 46
0

Another possible way to count the list of digits in PHP is:

// match only digits, returns counts
echo preg_match_all( "/[0-9]/", $str, $match ); 

// sum of digits
echo array_sum($match[0]);

Example:

$ php -r '$str="s12345abas"; echo "Count :".preg_match_all( "/[0-9]/", $str, $match ).PHP_EOL; echo "Sum :".array_sum($match[0]).PHP_EOL;'
Count :5
Sum :15
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36