Jeff
Jeff

Reputation: 4003

php adding up numbers

I think this might be an easy question for the professionals out there, but here goes.

Basically I want to get the total word count of a bunch of paragraphs. Right now I can get the word count of each paragraph, but I can't figure out how to add them all up.

$para // an array of paragraph strings

$totalcount = '';
foreach ($para as $p)
{
$count = str_word_count($p, 0);
 echo $count . "<br />";
 }
 print_r($totalcount);

this prints a list of 41 numbers, representing the word count of each pagraphs

but the $totalcount is an array of all these numbers. How can I get the sum of all 41 paragraphs?

Upvotes: 0

Views: 330

Answers (2)

Mark
Mark

Reputation: 502

You need to add to the total count each loop:

$para // an array of paragraph strings

$totalcount = 0;
foreach ($para as $p)
{
   $count = str_word_count($p, 0);
   echo "Count: ".$count . "<br />";
   $totalcount += $count;
}
echo "Total Count: ".$totalcount;

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318498

$totalcount = 0;
foreach(...) {
    $totalcount += $count;
}
echo $totalcount;

Upvotes: 2

Related Questions