00 Votes

PHP: Create any number of variables dynamically

Question by Axuter | 2012-04-27 at 21:12

I want to create a dynamic number of variables within a PHP script. Previously, I can not say exactly how many variables I will need.

Is there any function or writing in PHP for this?

PS: I know, that you can do something similar with an array and that certainly, in most cases, this is the more elegant solution, but I still need dynamically created PHP variables.

ReplyPositiveNegative
1Best Answer1 Vote

You can create variables with ${name} dynamically in PHP. Here is a small example:

// create $variable with content "Variable"
${variable} = 'Variable';
 
// create $variable1 to $variable5
for ($i = 1, $i <= 5; $i++) {
   ${variable.$i} = "Variable $i"
}
 
// output
echo $variable;   //"Variable"
echo $variable1;  //"Variable 1"
echo $variable2;  //"Variable 2"
echo $variable3;  //"Variable 3"
echo $variable4;  //"Variable 4"
echo $variable5;  //"Variable 5"

First, we create the variable $variable and assign a content to it. Then, we create 5 more variables in a loop and assign a dynamic content. Recently, we output the contents of the variables.
2012-04-29 at 12:15

ReplyPositive Negative
Reply

Related Topics

PHP: Current Date and Time

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.