Using Variable Variables in PHP

Last updated: Aug 5, 2008

When I was codeing I didn’t know how in the world I was going to be able to have incrementing variables in my code. That was until I searched the website and came up with variable variables. I had no idea what these were until now.

The problem

Recently I needed to loop through a few items in a shopping cart and send it through a function that encodes the data and sends it off to Google Checkout. The problem was that each function needed to be refrenced by a different variable name otherwise the items would all end up being the same.

When you want your variable names to change in PHP you need to use variable variables.

An example

$item = "item_$counter";
$total_count = $quantity;

$$item = new GoogleItem("$productName - $productSize",  // Item name
"product description", // Item description
$total_count, // Quantity
$price); // Unit price                                                                                                                                                                 $cart->AddItem($$item);

Basically what is happneing is my variable name is stored in a variable called $item. That variable is set to a value of item_$counter. In my loop this code will increment the counter and make a item_1, item_2, item_3 etc..

This is the first time I have encountered these gems. Anyone else have to use them?

Need to print shipping labels on your site?

Checkout my product RocketShipIt for simple easy-to-use developer tools for UPS™ FedEx™ USPS™ and more.

Get notified on new posts or other things I'm working on