2

I have this code:

echo $b1[1][wood];   // It would say 100

But i want to change the 1 in $b1, for example:

$id = 1;
echo $b(The $id here)[1][wood];

I tried

echo $b'.$id.'[1][wood];  

But it didnt work. Does any one have any suggestions ?

Thanks

2
  • 2
    Ick. Try to avoid "variable variables" - not many languages have such a construct, but work fine anyway. Don't confuse "convenient" (per the documentation's wording) with "appropriate". Commented Jun 2, 2013 at 0:15
  • Milan's answer below is perfect for this. however, I suggest you would want to try out using array instead. Commented Jun 2, 2013 at 4:59

3 Answers 3

5

Try this:

$id = 1;
echo ${'b'.$id}[1]['wood'];
Sign up to request clarification or add additional context in comments.

Comments

2

why don't you use an array() type ?

Comments

2

Try this:

$varName = 'b' . $id;
echo ${$varName}[1]['wood'];

(Notice I also put quotes around 'wood' - PHP treats wood as an undefined constant, which will work, but generates a warning)

A better solution would be to avoid variable variables altogether. Couldn't you just make $id another dimension of the array? $b[$id][1]['wood'] ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.