Jump to content

Archived

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

Aljade

Create Variables

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!

Share this post


Link to post
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]

Share this post


Link to post
Share on other sites

×

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.