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

Link to comment
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.