karisma
karisma

Reputation: 156

How to sum count variable in PHP

i want to sum for some data which come from function foreach in PHP, but i found error while run it, here my simple code :

        <?php
            $no=1;
            foreach($data_tersimpan->result_array() as $dp)
            {
            ?>
            <?php 
            $total = 0;
            $total += count($dp['id_plan']);
            echo $total;
        ?>
         <?php
                $no++;
            }
         ?>

from my code above, i print $total, then data shown like this :

1   1   1   1   1

I want to get summary 5 if i print $total is there any suggestion to make summary in php scrypt(not in sql query)?

THanks

Upvotes: 1

Views: 3250

Answers (4)

Nathan H
Nathan H

Reputation: 49371

That's because you are resetting your total for every iteration of the loop.

<?php
    $total = 0;
    $no=1;
    foreach($data_tersimpan->result_array() as $dp) {
        $total += count($dp['id_plan']);
        $no++;
    }
    echo $total;
?>

Upvotes: 4

Manikanta
Manikanta

Reputation: 313

<?php
    $no=1;
    $total = 0;
    foreach($data_tersimpan->result_array() as $dp) {
        $total += count($dp['id_plan']);
        $no++;
    }
    echo $total;
?>

Upvotes: 2

Shafiqul Islam
Shafiqul Islam

Reputation: 5690

your code have some problem first you add total and every time assign total 0 so total not update and no need more php tag and also counter value

<?php
$total = 0; // first assign total 0
foreach ($data_tersimpan->result_array() as $dp) {
    $total += count($dp['id_plan']); // every time update total  = total + your value;
}
echo $total; // this is final total
?>

when loop complete then final output is total value, if no data found then final total will be 0.

Upvotes: 2

jasinth premkumar
jasinth premkumar

Reputation: 1413

you have misplaced {}& opening tag for PHP within in your PHP code .which causes error.have you enabled ERROR_display in your PHP ini file?

  <?php
            $no=1;
            $total = 0;
            foreach($data_tersimpan->result_array() as $dp)
            {
            $total += count($dp['id_plan']);
             }
            echo $total;
        ?>

Upvotes: 2

Related Questions