Jump to content

Dynamically Add Number to End of Variable Name


JasonHarper

Recommended Posts

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

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.