I want to be able to name my variables with other variables like iterating through $var_1, $var_2, $var_3...
What I want to do is more complicated, and more useful, than the fallowing code but if I can accomplish the following then I'll be set.
$num=1;
do {
$var_$num=$num
$num++
} while ($num<5);
$num=1;
do {
echo $var_$num;
} while ($num<5);
I need to cycle through $var_1, $var_2, $var_3...
Naming variables with variables
Moderator: General Moderators
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
Generally when I see people doing this I come to the conclusion that it would be more sensible to use an array but in any case the syntax you're looking for is:
Code: Select all
$varname = 'foo';
${'prefix_'.$varname} = 42;
echo $prefix_foo;- Ollie Saunders
- DevNet Master
- Posts: 3179
- Joined: Tue May 24, 2005 6:01 pm
- Location: UK
wow d11wtq you just tought me a new syntax, I thought I knew all of those.
This is the other method you can use:
This is the other method you can use:
Code: Select all
$varName = 'foo';
$extended = 'prefix_' . $varName;
$$extended = 42;
echo $prefix_foo; // outputs 42
echo $$extended; // outputs 42
echo $extended; // outputs prefex_foo- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
Hehole wrote:wow d11wtq you just tought me a new syntax, I thought I knew all of those.
This is the other method you can use:Code: Select all
$varName = 'foo'; $extended = 'prefix_' . $varName; $$extended = 42; echo $prefix_foo; // outputs 42 echo $$extended; // outputs 42 echo $extended; // outputs prefex_foo
Code: Select all
function something_foo()
{
}
$func = 'foo';
{'something_'.$func}();- Ollie Saunders
- DevNet Master
- Posts: 3179
- Joined: Tue May 24, 2005 6:01 pm
- Location: UK
It's all written down in the section on variable variables in the php manual..
The following does work (i'll be honest, i don't know where this is documented)
The following does work (i'll be honest, i don't know where this is documented)
Code: Select all
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', TRUE);
function foo1() {
echo 'foo';
}
$a = 1;
$func = 'foo' . $a;
$func();
?>