1

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'];

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.