Jump to content

Create Variables


Aljade

Recommended Posts

Ok the best way to ask this is with an example.

[code]$variable_number = 0;
while($num < 10) {
   $variable_number++;
   //Here is want to create new variable called $variable[$variable_number]
}[/code]

I want to have this code create 10 variables called $variable1, $variable2, $variable3, etc.

I know it may seem to make more sense to create an array, however this will not work in my situation.

Thank you!
Link to comment
Share on other sites

See: [a href=\"http://us2.php.net/manual/en/language.variables.variable.php\" target=\"_blank\"]http://us2.php.net/manual/en/language.variables.variable.php[/a]


This creates 10 variables and initializes each one to zero:

[code]
for ($i = 1; $i < 11; $i++) {

    $var_name = 'a_name' . $i;

    $$var_name = 0;   // Creates variable called: $a_name1  through  10
   //     /\___ Must be referenced this way

}
[/code]

Another example:

[code]
$vars = array('a_name1' => 0,
                 'a_name2' => 0,
                 'a_name3' => 0
                );

extract ($vars);

echo $a_name1;   // <-- Can be referenced this way
[/code]

See extract() for more info:
[a href=\"http://us2.php.net/manual/en/function.extract.php\" target=\"_blank\"]http://us2.php.net/manual/en/function.extract.php[/a]


FYI: There's also import_request_variables() for get, post and cookie variables:

[a href=\"http://us2.php.net/manual/en/function.import-request-variables.php\" target=\"_blank\"]http://us2.php.net/manual/en/function.impo...t-variables.php[/a]
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.