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 trial

PHP Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Adding Elements and Specifying a Key

Declaring Array

At around 1.11 of the video it was mention that it is good practice to declare an empty array first than assign values to it, so instead of making an array like this:

$something = array(
 "value",
 "value",
 "value"
);

you do it like this:

$something = array();
$something[] = "value";
$something[] = "value";
$something[] = "value";

But why is that? isnยดt its easier to understand the first way?

2 Answers

Cindy Lea
PLUS
Cindy Lea
Courses Plus Student 6,497 Points

Yes you can do it the first way. Im guessing they are showing another way to do it & showing how it works in a "push" function so that you can see that you can add a value to the end of the array without keeping track of where it goes in the list. For example, if you already have 3 items in the array, you can add 3 more items doing the 2nd way without using indexes. Another reason for doing it the 2nd way is you may not know all your values up front. If an array is used for storing errors, you want to push those values on as you receive them & not have to worry about the index of where to add the value.

Ya, I'm not sure why the code is refactored here. First way seems better to me.

I thought so too, but as you use custom keys for the array, I can kinda understand her point. This way you can see which key corresponds to which value easily.