1

I made a loop then sum it into variable $jumlahtotal, what I confuse is the value in $jumlahtotal is true when I try to echo it, but I getting undefined variable error on this $jumlahtotal

Note : i tried declare it outside the foreach but still getting error undefined variable;

here's my code :

$total = 0;
    $totalberat = 0;
    if (isset($_SESSION['items'])) {
    foreach ($_SESSION['items'] as $key => $val) {
    $query = mysqli_query($koneksi, "select * from barang where br_id = '$key'");
        $data = mysqli_fetch_array($query);
        $jumlah_harga = $data['br_hrg']*$val;
        $total += $jumlah_harga;
        $berat = $data['brt_brg']*$val;
        $totalberat += $berat;
        $jumlahtotal += $val;
}}
?>
2
  • 1
    declare it outside the loop with the value of 0. Commented Dec 16, 2016 at 8:12
  • @MarkVincentManjac it work, I just know it must declared as 0 first before sum it, thx Commented Dec 16, 2016 at 8:21

1 Answer 1

1

Some tips:

Start declaring $jumlahtotal=0 above $totalberat.

$total = 0;
$totalberat = 0;
$jumlahtotal = 0;

Validate the value of $val before adding its value to $jumlahtotal.

if (is_int($val)) {
    $jumlahtotal += $val;
} else {
    die('$val not int');
}

If its all okay, debug the code and check the code is reaching the '$jumlahtotal += $val;' sentence and debug it.

$jumlahtotal += $val;
var_dump($jumlahtotal);

It should help you to find the issue.

Sign up to request clarification or add additional context in comments.

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.