Jump to content


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


Create Variables

Recommended Posts

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

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

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:

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


Another example:

$vars = array('a_name1' => 0,
                 'a_name2' => 0,
                 'a_name3' => 0

extract ($vars);

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

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.