Possibly the weirdest bug fix. 06-03-2014, 09:21 AM
#1
So, I had a PHP exam where I had to code a shopping cart class with functions to add and to calculate the total cost of the items in the cart (pretty basic stuff), and I removed a useless line of code after $total = 0;, but then the total cost of the items started to return 0, for no apparent reason.
So adding this line after $total = 0, somehow fixed it;
I don't even see how the above line of code does anything.
Spoiler:
PHP Code:
<?php
class shopping_cart
{
var $cart;
function addItem($id, $name = "undefined", $price = 0, $quantity)
{
$this->cart[$id] = array('name' => $name, 'price' => $price, 'quantity' => $quantity);
}
function getTotal() {
$total = 0;
$potato = $this->cart; //random glitch returns 0 when this line is not here.
while ($temp = current($this->cart)) {
if (!is_array($temp)) {
$total += key($this->cart).': '.current($this->cart);
} else {
$cache2 = current($this->cart);
$total += $cache2["price"]*$cache2["quantity"];
}
next($this->cart);
}
echo $total;
}
function outputCart() {
while ($temp = current($this->cart)) {
if (!is_array($temp)) {
$data[] = key($this->cart).': '.current($this->cart);
} else {
$part2 = current($this->cart);
while ($temp2 = current($part2)) {
$data[] = key($part2).': '.current($part2);
next($part2);
}
}
next($this->cart);
}
echo $data = implode ('<br/>', $data);
}
}
$shoppingCart = new shopping_cart;
$shoppingCart->addItem( 1, "Bacon", 10.40, 3);
$shoppingCart->addItem( 2, "Chocolate", 4.40, 2);
$shoppingCart->outputCart();
echo "<br/>total price: ";
$shoppingCart->getTotal();
?>So adding this line after $total = 0, somehow fixed it;
PHP Code:
$potato = $this->cart; //random glitch returns 0 when this line is not here.
I don't even see how the above line of code does anything.





![[+]](https://sinister.ly/images/modern/collapse_collapsed.png)




![[Image: BXqGARG.png]](https://i.imgur.com/BXqGARG.png)




![[Image: TeusoI9.png]](http://i.imgur.com/TeusoI9.png)








![[Image: Ov15OiO.png]](https://i.imgur.com/Ov15OiO.png)