14

My goal is to have a loop where variable names are created. Such as:

$variable1
$variable2
$variable3

and assigned values within the loop. For instance, a for loop from 1 to 7 produces the variables $variable1, $variable2, $variable3, .etc, each with the value of the iterator.

4
  • 9
    Use an array... Commented Jun 16, 2013 at 16:08
  • 1
    possible duplicate of how to change php variable name in a loop? Commented Jun 16, 2013 at 17:01
  • If you post the context of your actual problem, we may be able to provide alternative solutions which don't require this functionality and will lead to cleaner code. Commented Jun 16, 2013 at 17:32
  • Possible duplicate of how to change php variable name in a loop? Commented Mar 13, 2017 at 2:22

6 Answers 6

55

There are several ways. One is via a string and a double $, but I don't like this method. A programmer could easily remove the double $ (seeing it as a typeo).

for($i = 0; $i <= 7; $i++) {
     $name = "variable{$i}";
     $$name = "foo";
}

The best approach is the explicit statement.

for($i = 0; $i <= 7; $i++) {
     ${"variable$i"} = "foo";
}

With the explicit inline string there is no doubt about the intent of what you're doing. Another PHP programmer will not alter the code by mistake.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, for some reason, my first solution isn't working. Tried on multiple servers: ideone.com/rvJnj7. I've deleted my post.
@Nile I was about to comment on it: it looks like it would work, but it doesn't codepad.org/L6XYoGNM - PHP sees $variable{$i} as an attempt to index either an array element or a byte of a string in the variable $variable, just like $variable[$i] would be; given an unset value, it prefers an array. So you are actually initialising an indexed array here, not a set of named variables as requested.
17

You should use an array for this:

for($i = 1; $i <= 7; $i++) {
  $variable[$i] = $i;
}

Edit: to clarify, you should use an array because there's no code (to my knowledge) which will accept $variable1 but not $variable[1]. Dynamically generating variable names is all kinds of wrong.

8 Comments

@Kolink they are PHP's version of other languages inflection.
@MathewFoscarini I can't find any programming meanings of "inflection"; did you mean "reflection"? And if so, what does dynamically naming variables have to do with reflection (which, incidentally, PHP does support)?
@IMSoP inflection means to modify an object at run-time from it's original meaning. PHP is a dynamic language and was designed to do this kind of thing. While it's not a good idea it's also not a good idea to program in PHP ;)
+1 this is totally the right thing to do, but doesn't solve the OP's problem. Sadly, this is the life of a programmer.
@MathewFoscarini OK, I hadn't heard that definition. Not sure how it applies here, though, as we're not changing the meaning of a variable, we're naming variables at runtime, something with extremely limited uses.
|
5

Just to expand on what others have said about why this is a technique best avoided: variable names exist solely for use by the programmer; they have no relationships or properties according to the language's runtime. As such, a collection of related variables should be put into a variable representing some appropriate container - in the case of PHP, its incredibly flexible "array" type.

Whenever the issue of dynamically named variables is raised, it is usually because somebody thinks it is a solution to a particular problem, but it generally leads to more problems than it solves - for instance, once part of a program starts dynamically naming variables, everywhere that wants to use those variables now also has to dynamically name them; finding out which items are actually set becomes unnecessarily complex, and so on.

There are a very few contexts where variable-variables are useful, for certain kinds of debugging and meta-programming, for example, but like goto, their presence in the language should not mean you don't try every other possible solution first.

999 times out of 1000, though, if you find yourself wondering how to dynamically create variable names, you should reframe the question: what are you actually trying to achieve, and what is the best solution to that problem. If some existing / 3rd-party code has been built using this pattern (and presumably also global variables), it may be best to patch or wrap it rather than propogating the mis-design into your own code. (Admittedly, a wrapper will still need to know how to declare the dynamic variables.)

Comments

1

If you had an associative array i'ld prefer using the extract() method. Check it out here

for example

<?php

/* Suppose that $var_array is an array*/

$var_array = array("color" => "blue",
               "size"  => "medium",
               "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape";

?>

the above code would output, blue, large, sphere, medium

Comments

0

In case any one wants to do this through an object:

<?php 
        $x = 1;
        while($x <= 4){
        echo $q->{"a$x"}; 
        $x++;
?>

Comments

-16

Thats no possible since variable cannot be create in run time

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.