Jump to content


Photo

Create Variables


  • Please log in to reply
1 reply to this topic

#1 Aljade

Aljade
  • New Members
  • Pip
  • Newbie
  • 6 posts

Posted 01 May 2006 - 12:38 AM

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

$variable_number = 0;
while($num < 10) {
   $variable_number++;
   //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!

#2 toplay

toplay
  • Staff Alumni
  • Advanced Member
  • 973 posts

Posted 01 May 2006 - 12:45 AM

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]




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users