0

I have a problem using an array within a foreach within a class. I get the warning..

PHP Warning: Invalid argument supplied for foreach()

on line

foreach($this->recordOfDiscounts as $key => $discount)

The problematic function is below,

public function modify_price( $price, $product_id ) {
    foreach($this->recordOfDiscounts as $key => $discount) {
        foreach($discount['get_one_free'] as $id) {
            if($id == $product_id){
                if( $discount['valid'] > 0 ) {
                    $price -= $discount['cost'];
                    $this->recordOfDiscounts[$key]['valid'] -= 1;
                }
            }
        }
    }
    return $price;
}

I'm new to PHP, but what I've gathered is that the class scope ($this->) needs to prefix a var within a class.

error_log(print_r($this->recordOfDiscounts),0);

outputs the correct array info, so I know its defined.

Array
(
    [0] => Array
        (
            [valid] => 1
            [buy_one] => 2351
            [cost] => 20
            [old_cost] => 20
            [get_one_free] => Array
                (
                    [0] => 2471
                    [1] => 2470
                    [2] => 2472
                    [3] => 2473
                    [4] => 2474
                    [5] => 2475
                    [6] => 2476
                    [7] => 2477
                )

        )

)
1
  • Where did you output to the error_log? Try outputting the contents of $this->recordOfDiscounts on the first line of your modify_price function. Commented Jan 9, 2013 at 11:17

1 Answer 1

2

One of the foreach statements has something non-iterable as the first part of the statement.

Either $this->recordOfDiscounts is not an array, or on one iteration of the outer foreach, $discount['get_one_free'] is not iterable.

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

1 Comment

sorry, i've edited the question to be more specific.The warning occurs on the line foreach($this->recordOfDiscounts as $key => $discount).

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.