Coder, Entrepreneur, Blogger, and Coffee Addict
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 php.net website and came up with variable variables. I had no idea what these were until now.
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.
$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?
Comments are closed.
© 2011 All rights reserved