title: How to create variables and assign them values within a for each loop in PHP?
body: <p>I have  for each loop which when looping outputs the items held in a basket array. This works great, but I want to store a few things per EACH item in session variables so I can use this information elsewhere, I am trying to create session variables inside the foreach loop, but of course the variables need to have different names every time it loops through a different item. I have researched how to create variables dynamically, I couldn't figure it out. This is something I have always felt would come in handy, but as it seems difficult I just avoid it, but now I want to know if its possible.</p>
  
  <p>Here is my for each loop code, you can see inside the three session variables I want to create for each item in the basket:</p>
  
  <pre><code>foreach ($basketarray as $value)
  {
      echo "&lt;div id='basketitems'&gt;&lt;br/&gt;                                       
      ".$value['name']."&lt;br/&gt;
      ".$value['id']."&lt;br/&gt;
       &amp;pound;".$value['price']."&lt;br/&gt;
       ".$value['size']."&lt;br/&gt;
      Quantity: ".$value['quantity']."&lt;br/&gt;&lt;br/&gt;
      &lt;img id='searchimage' src=".$value['picture']." width='210' height='250' /&gt;&lt;br/&gt;";
  
      $_SESSION['Bprodid'] = $value['id'];
      $_SESSION['Bprodquantity'] = $value['quantity'];
      $_SESSION['Bprodprice'] = $value['price'];
  
  echo "&lt;form action='deletefrombasket.php' name='basketdelete$items' id='basketdelete$items' method='POST'&gt;
  
      &lt;input type='submit' name='".$value['basketid']."' value='Remove' id='basketid' name='basketid'/&gt;
  
      &lt;/form&gt;&lt;/div&gt;";
  
  $items++;
  }
  ?&gt;
      &lt;div id='basketdetails'&gt;
  &lt;?php
  
  echo "&lt;p&gt;items ". number_format($basketitems)."&lt;/p&gt;";
  echo "&lt;p&gt;Total &amp;pound; ".number_format($baskettotal, 2, '.', ',')."&lt;/p&gt;";
  
  
  if($basketitems &amp;&amp; $baskettotal !=0)
  {
      echo "&lt;a  href='clear.php'&gt;Empty Basket&lt;/a&gt;";
      echo "&lt;a  href='checkout.php'&gt;Checkout&lt;/a&gt;";
  }
  </code></pre>
  
  <p>So it is possible to do something like this? I was trying to create varaible names by using a counter but I was unsuccessful.</p>
  
  <p>I would appreciate any advice.</p>
  
  <p>Thanks</p>