I have an array, I need to copy the first item in the array and alter it.
This is what i'm doing:
echo $QuantityDiscounts[0]['price'] . '<br>';
echo $QuantityDiscounts[0]['from_quantity'] . '<br>';
$firstItem = $QuantityDiscounts[0];
$firstItem['from_quantity'] = 999;
$firstItem['price'] = 999;
echo $QuantityDiscounts[0]['price'] . '<br>';
echo $QuantityDiscounts[0]['from_quantity'] . '<br>';
This is the output this gives me:
4.870000
10
4.870000
999
When I change the value of the copied array it's changing the original array. What makes this even stranger is that it only happens for the 'from_quantity' item. As you can see the 'price' element remains unaltered.
I can't figure out why this is happening, as you can see i'm not using references. Is there an explanation for this behaviour that i'm missing?
Some more info:
If I first copy the 'from_quantity' in the original array so that it uses a different key this behaviour goes away.
$QuantityDiscounts[0]['test'] = $QuantityDiscounts[0]['from_quantity'];
echo $QuantityDiscounts[0]['price'] . '<br>';
echo $QuantityDiscounts[0]['from_quantity'] . '<br>';
echo $QuantityDiscounts[0]['test'] . '<br>';
$firstItem = $QuantityDiscounts[0];
$firstItem['from_quantity'] = 999;
$firstItem['test'] = 999;
$firstItem['price'] = 999;
echo $QuantityDiscounts[0]['price'] . '<br>';
echo $QuantityDiscounts[0]['from_quantity'] . '<br>';
echo $QuantityDiscounts[0]['test'] . '<br>';
Outputs:
4.870000
10
10
4.870000
999
10
** UPDATE ** - Thanks for your help so far
Here is the function that generates the array. I can see that a reference is being used there which must be causing the problems. Does this mean I can't copy and modify the 'from_quantity' without changing the original?
protected function formatQuantityDiscounts($specific_prices, $price, $tax_rate, $ecotax_amount)
{
foreach ($specific_prices as $key => &$row)
{
$row['quantity'] = &$row['from_quantity'];
if ($row['price'] >= 0) // The price may be directly set
{
$cur_price = (Product::$_taxCalculationMethod == PS_TAX_EXC ? $row['price'] : $row['price'] * (1 + $tax_rate / 100)) + (float)$ecotax_amount;
if ($row['reduction_type'] == 'amount')
$cur_price -= (Product::$_taxCalculationMethod == PS_TAX_INC ? $row['reduction'] : $row['reduction'] / (1 + $tax_rate / 100));
else
$cur_price *= 1 - $row['reduction'];
$row['real_value'] = $price - $cur_price;
}
else
{
if ($row['reduction_type'] == 'amount')
$row['real_value'] = Product::$_taxCalculationMethod == PS_TAX_INC ? $row['reduction'] : $row['reduction'] / (1 + $tax_rate / 100);
else
$row['real_value'] = $row['reduction'] * 100;
}
$row['nextQuantity'] = (isset($specific_prices[$key + 1]) ? (int)$specific_prices[$key + 1]['from_quantity'] : -1);
}
return $specific_prices;
}