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 trialAndrew Hunt
7,665 PointsAdding element to array - why won't this work?
I'm confused - I'm trying to complete this challenge by adding the key "title" to an array of $movies. I've tried to follow the example as per the media library site but can't pass this. I've seen other solutions elsewhere using the array(); formatting so may have to use that in order to pass. I don't understand why this solution won't work as well though?
<?php
$movie = [];
$movie[] = [
"title" => "The Empire Strikes Back",
];
?>
<h1>Back to the Future (1985)</h1>
<table>
<tr>
<th>Director</th>
<td>Robert Zemeckis</td>
</tr>
<tr>
<th>IMDB Rating</th>
<td>8.5</td>
</tr>
<tr>
<th>IMDB Ranking</th>
<td>53</td>
</tr>
</table>
2 Answers
andren
28,558 PointsOften times these challenges will be looking for specific code, which means that even if the result is right the code might still be marked as wrong. It's important to note thought that this is not the case here. Your code does actually do something different from what the task is asking.
When you use [] after an array name when assigning a value, you are telling PHP to add the thing you specify to the array. Since the thing you specify is not a single value, but an array itself, you are actually telling PHP to add the entire array as an item inside of your array. Which means that after running your code the movie
array will look like this:
array(1) {
[0]=>
array(1) {
["title"]=>
string(23) "The Empire Strikes Back"
}
}
In other words your array has an array nested within itself as the first item. Which is clearly not quite what the challenge is asking for.
If you remove the brackets like this:
$movie = [
"title" => "The Empire Strikes Back",
];
Then it will work correctly as you are now simply setting the variable to an array, instead of telling PHP to add the value as an array item.
Andrew Hunt
7,665 PointsAha, thanks andren, I can see where I was going wrong now - that's very helpful!