0

I am a newbie to PHP and trying out some things to see they work .. I have tried lots of different attempts at this .. but no luck .. It is supposed to echo output 2 .. !!! I keep getting errors.

<?php

$a = array('x' => array('y' => 1, 'z' => 2, 'q' => 3,));

echo {$a['z']};//echo the value 2 from $a (tried this and it did not work.  

?>
1
  • try $a['x']['z'] because its a multidimensional array and without brackets: echo $a['x']['z']; Commented Jan 14, 2013 at 10:40

5 Answers 5

5

Since you have an array within an array, you need to do:

echo $a['x']['z'];
Sign up to request clarification or add additional context in comments.

Comments

2

You are using an associative array, and your syntax is incorrect.

To get to z you need to go through x:

echo $a['x']['z'];

The curly braces syntax is only used when you want to access an array (called array dereferencing) inside a string (which is called variable interpolation):

echo "The value is: {$a['x']['z']}";

If you are not dereferencing a variable using the square brackets then you do not need the curly braces:

$value = $a['x']['z'];
echo "The value is: $value";

Also, you mention that you get errors. Learn what they mean and you will be able to help yourself. If you ask for help then it would also be a good idea to tell us about the errors you are getting.

Comments

0

Try this without braces

echo $a['z'];

Or no, you have two arrays

try

echo $a["x"]["z"];

Comments

0

Try simply:

<?php

$a = array('x' => array('y' => 1, 'z' => 2, 'q' => 3,));

echo $a['x']['z'];

?>

Comments

0

You array is multi-dimensional, so you have to provide two indexes:

echo $a['x']['z']; // echoes 2

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.