JasonHarper Posted July 23, 2010 Share Posted July 23, 2010 Hello! I'm having a mental block and can't seem to accomplish the below: I have variables named in this fashion: $item1, $item2, $item3, $item4, $item5, etc. I'm retrieving values from a database and have a variable to hold an item count. Example: $itemCount = 1; //DO DATABASE STUFF $itemCount++; What I would like to do is assign values to the item variables based on the item count (i.e., if $itemCount were to be currently set to 5, it would assign the value retrieved from the DB to the variable $item5). I can't seem to figure out how to do this... Thank you for any help!! Jason Link to comment https://forums.phpfreaks.com/topic/208682-dynamically-add-number-to-end-of-variable-name/ Share on other sites More sharing options...
PFMaBiSmAd Posted July 23, 2010 Share Posted July 23, 2010 Please, just use an array - $item[1], $item[2], ... your code will be simpler and it will execute 3x faster than using the code needed to create a series of numbered variables. Link to comment https://forums.phpfreaks.com/topic/208682-dynamically-add-number-to-end-of-variable-name/#findComment-1090220 Share on other sites More sharing options...
JasonHarper Posted July 23, 2010 Author Share Posted July 23, 2010 That worked - thank you! Link to comment https://forums.phpfreaks.com/topic/208682-dynamically-add-number-to-end-of-variable-name/#findComment-1090386 Share on other sites More sharing options...
gizmola Posted July 23, 2010 Share Posted July 23, 2010 You got good advice, but just in case you were wondering, PHP allows for this type of syntax: $basename = 'foo'; for ($x = 1; $x $tempname = $basename . $x; $$tempname = $x; } echo "$foo1 \n"; echo "$foo2 \n"; echo "$foo3 \n"; //etc This isn't used much because it makes for some very confusing and convoluted code, but the '$$' syntax does work. Link to comment https://forums.phpfreaks.com/topic/208682-dynamically-add-number-to-end-of-variable-name/#findComment-1090392 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.