Norman
Norman

Reputation: 6365

Variable Variable wont work with array

I'm trying to do a variable variable, but it wont work when I use it in the code below.

I keep getting:

Notice: Undefined variable: C in C:\web\apache\htdocs\cats-test.php on line 8

This only wont work when used with an array. Can you help?

$Consumer = array(
"a" => "Apparel",
"b" => "Books & Stationary",
);
$cat = "Consumer";

echo $$cat['a']; //I'm trying to make this $Consumer['a'];

Upvotes: 1

Views: 62

Answers (3)

Thomas Ruiz
Thomas Ruiz

Reputation: 3661

Be aware of operator priorities. ${$cat}['a'] should work better.

Upvotes: 1

deceze
deceze

Reputation: 522155

echo ${$cat}['a'];

It's ambiguous whether you mean $$cat ['a'] or $ $cat['a']. Use brackets.

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270637

When accessing an array key in a variable variable, enclose the variable in {} to be certain that PHP expands the correct set of characters ($cat) as a variable.

echo ${$cat}['a'];
// Apparel

Upvotes: 0

Related Questions