Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialrob111
8,379 PointsHow to print "$cars[2][1]<br>";
Trying to figure out why
print "$cars[2][1]<br>";
does not display "BMW"
Any ideas?
It displays "Array[1]" instead.
<?php
$cars = array(
array('Toyota', '1994', '3,000'),
array('BMW', '2005', '20,000'),
array('Ford', '2001', '12,000')
);
?>
<?php
print "$cars[2][1]<br>";
?>
2 Answers
Jason Anello
Courses Plus Student 94,610 PointsHi Rob,
If you want array variables to be evaluated within double quotes then you have to wrap it in curly braces.
Like this:
print "{$cars[2][1]}<br>";
Or you could do string concatenation.
print $cars[2][1] . "<br>";
Also, with these indexes you'll get "2001" not "BMW"
Index 2 will access the "Ford" array and then index 1 will access the 2nd element of that array.
rob111
8,379 PointsOK thanks. Is there any reference material you can point me to so I can find out more about why {} are needed.
Jason Anello
Courses Plus Student 94,610 PointsIt mentions it in example 4 on this page: http://php.net/manual/en/function.array.php
As in Perl, you can access a value from the array inside double quotes. However, with PHP you'll need to enclose your array between curly braces.
The string parsing section here, http://php.net/manual/en/language.types.string.php#language.types.string.parsing, has more details.