• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 421
  • Last Modified:

PHP Variable in a Loop?

Is it possible to create 100's of variables with a loop?  The loop I'm using really cuts down on the code in the page, but I lose all my variables that I need to reference.  Here is what I was thinking.

if $variable < 365 {
$variablenumber = 1;
$variablename{$$variablenumber} = (variablenumber + 1);
} else {
echo "all done";

Is this possible?

So, the result would be these answers:
$variablename1 = 1
$variablename2 = 2
$variablename3 = 3
$variablename365 = 365
1 Solution
Guy Hengel [angelIII / a3]Billing EngineerCommented:
>Is it possible to create 100's of variables with a loop?
why not a plain array?

$variablename = array();
for ($i=1; $i<366; $i++)
  $variablename[$i] = $i;
//to show the results_

Open in new window

I assume you've looked at an array... $var[$x].

But this should do what you wanted:
$GLOALS['varname'.$variablenumber] = $variablenumber;

you'll get $varname1 = 1, $varname2 = 2,  
and they are all globals.


try this

for ($variablenumber=1; $variablenumber<=365 ;$variablenumber++)
  $variablename = 'variablename'.$variablenumber;
  $$variablename = $variablenumber;
echo "var50=".$variablename50 ."<br />\n";
echo "var72=".$variablename72 ."<br />\n";
echo "var321=".$variablename321 ."<br />\n";

Open in new window

Train for your Pen Testing Engineer Certification

Enroll today in this bundle of courses to gain experience in the logistics of pen testing, Linux fundamentals, vulnerability assessments, detecting live systems, and more! This series, valued at $3,000, is free for Premium members, Team Accounts, and Qualified Experts.

bschwartingAuthor Commented:
I could only get Michaels701 to work.  Thanks all!
Guy Hengel [angelIII / a3]Billing EngineerCommented:
yes, that code will do what you asked.

however, still curious about the why you need that in your code?
it really looks like you are doing something wrong in your method...
bschwartingAuthor Commented:
angel, I wouldn't doubt it.  I'm just past a beginner on PHP.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now