rat4m3n
rat4m3n

Reputation: 1201

foreach loop adding value within the loop

It seems very basic, but I stuck on this one.

$value = 0;
foreach($this->products->result() as $this->product)
{
    $value += $this->product->price;
}
//$value += $this->get_order_shipping_cost($orders_id);

return $value;

The value supposed to get added to create total price and then outside the loop to add a shipping cost, but for some reason my loop is returning only the first value, so I am overwriting something somewhere.

Upvotes: 0

Views: 1455

Answers (2)

hakre
hakre

Reputation: 197682

You are setting a private member of your class while you only want to get the product and that's it. You don't need to use $this->product, just use a free variable instead, like $product and it should work:

$value = 0;
foreach($this->products->result() as $product)
{
    $value += $product->price;
}

Also if products is one of your objects, you should give it probably a method like getTotalPrice() which just returns the sum, like so:

$value = $this->products->getTotalPrice();

You can then use that more flexible within your code. Hope this is helpful.

Upvotes: 0

Stefan Koenen
Stefan Koenen

Reputation: 2337

i think this is where the overwrite heapens:

foreach($this->products->result() as $this->product)

i don't know what you're doing before but maybe you could use a temp variable name in the for loop like this:

foreach($this->products->result() as $tempProduct)
{
    $value += $tempProduct->price;
}

hope it works ;) greets, stefan

Upvotes: 3

Related Questions