3

I've got a small problem. I'm working on a little package/product-list. If you're watching a Package, my website should show you which products are in there. If a product is more than one time in it, the array should be deleted and the value of the leftover array should be + 1 (each deleted array).

So here's my code:

// $products_in_package has all products in it
// First of all, the products come from a db and don't have a count
// So i first give them a count of 1

foreach ($products_in_package as $product => $value) {
    $products_in_package[$product]['count'] = intval(1);
}

foreach ($products_in_package as $product) {
    $id_to_find = intval($product['ID']);
    $product_count = intval($product['count']);
    $found_id = 0;
    // Now I try to find any ident products
    // If found and over 1 time (beacouse he finds the first too of course)
    // Then delete this array and count up the products count

    for ($i=0; $i <= count($products_in_package); $i++) {
        if(intval($products_in_package[$i]['ID']) === $id_to_find){
            $found_id++;

            if($found_id > 1){
                $product_count = $product_count + 1;
                $product['count'] = $product_count;
                unset($products_in_package[$i]);
                array_merge($products_in_package);

                while($i > $products_in_package){
                    $i = 0;
                }
            }
        }
    }
}

What I'm getting is the correct multidimensional array but the count is still 1. What's wrong with the code?

Everytime I try to log the code i'm getting the right integer. (No, I already tried to delete the chache) But if I log the array out of the loops, I get always the count of 1.

1 Answer 1

3

$product is a copy of the array element, so when you do $product['count'] = $product_count you're assigning to a copy, not the original array.

You can fix this by using a reference in the foreach:

foreach ($products_in_package as &$product) {
Sign up to request clarification or add additional context in comments.

3 Comments

Oh.. wow.. I didn't know that the answer is so easy. I didn't know that I'm assigning to a copy.. why's that? I'm a fresh student of webdesign and i never heard about that :(
Except for objects, all assignments in PHP make copies.
Oh.. and thank you much :) i tried hours and nothing happened

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.