fedejp
fedejp

Reputation: 970

Using array value with index as Variable Variable

The title may be a little confusing. This is my problem:

I know you can hold a variable name in another variable and then read the content of the first variable. This is what I mean:

$variable = "hello"
$variableholder = 'variable'
echo $$variableholder;

That would print: "hello". Now, I've got a problem with this:

$somearray = array("name"=>"hello");
$variableholder = "somearray['name']"; //or $variableholder = 'somearray[\'name\']';
echo $$variableholder;

That gives me a PHP error (it says $somearray['name'] is an undefined variable). Can you tell me if this is possible and I'm doing something wrong; or this if this is plain impossible, can you give me another solution to do something similar?

Thanks in advance.

Upvotes: 0

Views: 3197

Answers (2)

Lusitanian
Lusitanian

Reputation: 11132

How about this? (NOTE: variable variables are as bad as goto)

$variablename = 'array';
$key = 'index';

echo $$variablename[$key];

Upvotes: 1

miku
miku

Reputation: 188194

For the moment, I could only think of something like this:

<?php 
    // literal are simple
    $literal = "Hello";
    $vv = "literal";
    echo $$vv . "\n";
    // prints "Hello"


    // for containers it's not so simple anymore
    $container = array("Hello" => "World");
    $vv = "container";

    $reniatnoc = $$vv;
    echo $reniatnoc["Hello"] . "\n";
    // prints "World"
 ?>

The problem here is that (quoting from php: access array value on the fly):

the Grammar of the PHP language only allows subscript notation on the end of variable expressions and not expressions in general, which is how it works in most other languages.

Would PHP allow the subscript notation anywhere, one could write this more dense as

echo $$vv["Hello"]

Side note: I guess using variable variables isn't that sane to use in production.

Upvotes: 1

Related Questions