1

I was working OpenCart and added such code to Controller to show all the manufacturers to User:

  $this->load->model("catalog/manufacturer");
  $manufacturers = $this->model_catalog_manufacturer->getManufacturers();
  $allbrands = array();
  foreach ($manufacturers as $brand)
  {
    $brand["url"] = $this->url->link("product/manufacturer/product&manufacturer_id=".(string) $brand["manufacturer_id"],"","SSL");
    $allbrands[] = $brand;
  }

  $this->data["manufacturers"] = $allbrands;

It worked just fine but my previous code didn't work which is below:

  $this->load->model("catalog/manufacturer");
  $manufacturers = $this->model_catalog_manufacturer->getManufacturers();
  $allbrands = array();
  foreach ($manufacturers as $brand)
  {
    $brand["url"] = $this->url->link("product/manufacturer/product&manufacturer_id=".(string) $brand["manufacturer_id"],"","SSL");
  }

  $this->data["manufacturers"] = $manufactures;

What I was thinking is arrays are objects so they are pointed at references so if I change $brand variable then $manufacturers will also have arrays that have "url" as index but didn't work and PHP complains that it doesn't have any "url" index.

Assigning a new index to an array cause it to be recreated with new object in the heap or it extends the current object's place in the heap?

Any ideas, what might it happen?

2 Answers 2

2

foreach [docs] is creating copies of the array values:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

and

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

This should work:

foreach ($manufacturers as &$brand) {
    $brand["url"] = $this->url->link("product/manufacturer/product&manufacturer_id=".(string) $brand["manufacturer_id"],"","SSL");
}
unset($brand);
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome answer is awesome. Thnaks.
1

foreach creates a temporary copy of the objects. Its not a good idea to modify the arrays being referenced in the foreach inside the loop.

You should use pointers to do the modification inside the loop.

Here is an example copied from the docs.

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

Comments

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.