I'm making a PHP shopping cart and i'm trying to add the total price.
When i want to use $total i get this error: Undefined variable: total. Why doesn't this work? How can i get this to work? 
Code:
function cart() {
include 'dbh.inc.php';
foreach($_SESSION as $name => $value) {
    if($value > 0) {
        if(substr($name, 0,5)=='cart_') {
            $id = substr($name, 5, strlen($name)-5);
            $sql = "SELECT * FROM menuitem WHERE menuitem_id = '$id'";
            $result = mysqli_query($conn, $sql);
            while ($sqlResult = mysqli_fetch_assoc($result)) {
            $sub = $sqlResult['price_medium'] * $value;
                echo '
                        <td>' .  $sqlResult['productname'] . '</td>
                        <td>' .  $value . '</td>
                        <td>€ ' .  $sqlResult['price_medium'] . '</td>
                        <td>€ ' .  $sub . '</td>
                        <td><a href="includes/add-to-cart.inc.php?remove=' . $id . '">[-] </a><a href="includes/add-to-cart.inc.php?add=' . $id . '">[+] </a><a href="includes/add-to-cart.inc.php?delete=' . $id . '">[x]</a>
                      </tr>
                ';
            }
        }
        $total += $sub;
    }
}
echo $total;
}
EDIT for Chris:
I now have this:
function cart() {
include 'dbh.inc.php';
foreach($_SESSION as $name => $value) {
    if($value > 0) {
        if(substr($name, 0,5)=='cart_') {
            $id = substr($name, 5, strlen($name)-5);
            $sql = "SELECT * FROM menuitem WHERE menuitem_id = '$id'";
            $total = 0;
            $result = mysqli_query($conn, $sql);
            while ($sqlResult = mysqli_fetch_assoc($result)) {
            $sub = $sqlResult['price_medium'] * $value;
                echo '
                        <td>' .  $sqlResult['productname'] . '</td>
                        <td>' .  $value . '</td>
                        <td>€ ' .  $sqlResult['price_medium'] . '</td>
                        <td>€ ' .  $sub . '</td>
                        <td><a href="includes/add-to-cart.inc.php?remove=' . $id . '">[-] </a><a href="includes/add-to-cart.inc.php?add=' . $id . '">[+] </a><a href="includes/add-to-cart.inc.php?delete=' . $id . '">[x]</a>
                      </tr>
                ';
            }
        }
        $total += $sub; 
    }
}
echo $total;
}

