Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First element of the array $$foo

Tags:

arrays

php

I'm in trouble with this one. I've got a bunch of arrays decide on 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 ;-)

like image 522
tamasgal Avatar asked Jun 03 '26 00:06

tamasgal


2 Answers

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];
like image 100
meagar Avatar answered Jun 05 '26 14:06

meagar


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).

like image 32
ircmaxell Avatar answered Jun 05 '26 14:06

ircmaxell