I'm in trouble with this one. I've got a bunch of arrays decide on开发者_JS百科 runtime which one I want to use with the double '$'.
So if $foo
is 'bar'
, I get the array $bar
with $$foo
.
This works fine but how do I get the first element of $bar? $bar[0] is the way, but $$foo[0]
simply doesn't give any output.
Can anyone help me?
(I know it's a really bad style but the code is already done by someone else and I have to extend it here and there. I'm not going to rewrite all the code structure ;-)
Use braces around the inner $foo
:
echo ${$foo}[0];
You can do the same when the sub-variable in a variable-variable expansion is more complex:
$array1 = array('a');
$array2 = array('b');
$array3 = array('c');
// writes 'abc'
for ($i = 1; $i <= 3; ++$i)
echo ${'array' . $i}[0];
Please do not do this. Variable-variables are always a bad idea. There are better ways of solving the problem (such as arrays). Using the variable variables makes your code murkier and harder to understand. Not to mention potential security impacts it may have. Just avoid them, it's better in the long run...
Note that I'm only talking about variable variables, not variable object members and methods ($foo->$bar
and $foo->$method()
)... I use them all the time (although even that has some drawbacks).
I'm in trouble
indeed you are.
I've got a bunch of arrays
That's your problem.
Array should be ONE. A nested one.
So, you will need just
$data[$foo][0]
$var = $$foo;
echo $var[0]; // do whatever you want with that
精彩评论