GorillaApe
GorillaApe

Reputation: 3641

PHP variable scope confused

Hello
Here is my code.... THe problem is at $product variable.
Is there any way to fix this?
It is defined two times and causes problem overwrites

THE PROBLEM UPDATED

   $productsIDs = array();
        foreach ($rowsProducts as &$product) {
            $product["features"] = &$productsFeatures[$product["product_id"]];
            $productsIDs[] = $product["product_id"];
        }

//GET STOCK FEATURES
$sqlIds=implode(",",$productsIDs);
$sql="SELECT * FROM eshop_products_stock WHERE product_id IN ($sqlIds)";

$productsStock = $db->getRecordSet($sql);
$sql="SELECT * FROM `eshop_features_valuestr` WHERE feature_id IN ".
      "(SELECT DISTINCT feature1_id FROM eshop_products_stock WHERE product_id IN ($sqlIds))" .
        " AND language_code='$lang'";

$productsSizes = $db->getRecordSet($sql);
 $sql="SELECT * FROM `eshop_features_valuestr` WHERE feature_id IN ".
      "(SELECT DISTINCT feature2_id FROM eshop_products_stock WHERE product_id IN ($sqlIds))".
        " AND language_code='$lang'";;
$productsColors = $db->getRecordSet($sql);

$productsSizesV=array();
foreach($productsSizes as $size)
{
    $productsSizesV[$size["value"]]=$size["title"];
}

$productsColorsV=array();
foreach($productsColors as $color)
{
    $productsColorsV[$color["value"]]=$color["title"];
}
//Group by product stock
$productsStockV=array();
$product="";

foreach($productsStock as $product)
{
   $productsStockV[$product["product_id"]]["sizes"][]=$product["feature1_value"];
   $productsStockV[$product["product_id"]]["colors"][]=$product["feature2_value"];
}

Upvotes: 0

Views: 722

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318788

You've encountered a very nice php WTF: foreach ($rowsProducts as &$product) makes $product a reference. Not only for the loop but forever. If you then use a foreach using $product as the loop variable later (or do anything writing to $product), it will overwrite the last item of the first foreach loop.

Simply use foreach ($rowsProducts as $key => $product) and assign $rowsProducts[$key] = $product; at the end of your loop body if you changed anything.

Another solution would be calling unset($product); after your first loop to get rid of the reference. But generally not using reference loops is safer as you cannot forget to unset.

Upvotes: 3

codaddict
codaddict

Reputation: 455440

You should unset $product after the foreach loop:

foreach ($rowsProducts as &$product) {
      $product["features"] = &$productsFeatures[$product["product_id"]];
      $productsIDs[] = $product["product_id"];
}
unset($product);

Upvotes: 4

Related Questions