How do I name these php variables
I want to use a forloop to create a number of vars... their names are $var1
to $var15
. How do I do that? I'm doing $$开发者_JAVA技巧var.$i
but it's not working.
for($i=1; $i <= 15; $i++){
$$var.$i = 'this is the content of var'.$i;
}
If you wanted to do that, exactly, you would have to do ${$var . $i}
instead. Right now it's being interpreted as ($$var).$i
.
However, this is very bad style. Instead, you should use an array[php docs] to store the values:
$var = array();
for($i=1; $i <= 15; $i++){
$var[$i] = 'This is the content of $var['.$i.'].';
}
var_export($var);
Output:
array (
1 => 'This is the content of $var[1].',
2 => 'This is the content of $var[2].',
3 => 'This is the content of $var[3].',
4 => 'This is the content of $var[4].',
5 => 'This is the content of $var[5].',
6 => 'This is the content of $var[6].',
7 => 'This is the content of $var[7].',
8 => 'This is the content of $var[8].',
9 => 'This is the content of $var[9].',
10 => 'This is the content of $var[10].',
11 => 'This is the content of $var[11].',
12 => 'This is the content of $var[12].',
13 => 'This is the content of $var[13].',
14 => 'This is the content of $var[14].',
15 => 'This is the content of $var[15].',
)
This is more efficient and often safer.
精彩评论