1

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

8
  • You want total to be 5, or you want a separate variable (summary) to be 5? Commented Dec 7, 2017 at 7:49
  • $total to be 5 Commented Dec 7, 2017 at 7:49
  • You didnt close the foreach Commented Dec 7, 2017 at 7:50
  • 3
    Then put $total = 0; before the loop, your resetting it each time to 0 Commented Dec 7, 2017 at 7:50
  • 1
    define this $total = 0; out side of foreach and echo $total; after closing foreach you get count of total Commented Dec 7, 2017 at 7:51

4 Answers 4

4

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;
?>
Sign up to request clarification or add additional context in comments.

Comments

2

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;
        ?>

Comments

2

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.

1 Comment

sorry for accept answer i vote to the first time answer :)
2
<?php
    $no=1;
    $total = 0;
    foreach($data_tersimpan->result_array() as $dp) {
        $total += count($dp['id_plan']);
        $no++;
    }
    echo $total;
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.