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 trialLucas Krause
19,924 PointsWhy is it good practice to declare an empty array and then push the items to that array?
It's a good practice to declare products first as an empty array.
What's the advantage over declaring and filling the array in one step?
2 Answers
Thomas King
15,197 PointsWhen you declare an empty array from the start, and THEN fill the array with data later on in the program, you prevent multiple errors from occurring because of a faulty array.
It is useful to know that the information you are using is bugged, rather than to have the array itself be bugged. It saves you some time debugging your program.
Philip Cox
14,818 PointsYou cannot push to an array that does not exist :)
Lucas Krause
19,924 PointsEhm yes, that's correct. But I didn't say that the array doesn't exist. I just said that it's empty. ;)
Philip Cox
14,818 PointsI see what your saying :). Most of the time you may not have anything to add to your array at the point of creation. But the array needs to be pre created ready to populate.
Lucas Krause
19,924 PointsWell that would be a reason for defining an empty array and filling it separately. But the quote was related to something like this:
$a=array();
$a[]="one";
$a[]="two";
$a[]="three";
instead of:
$a=array(
"one",
"two",
"three"
);
To me there seems to be no reason to use the first way, especially because the contents do already exist. Or am I wrong? :D
Philip Cox
14,818 PointsI would say the first way looks like what happens behind the scenes of a loop cycle pushing to an array, but no you would never really need to write it like this, that would not be very DRY at all.
Lucas Krause
19,924 PointsMy saying :D
Lucas Krause
19,924 PointsLucas Krause
19,924 PointsThanks for your response. Is that the only reason? I think the error messages will be very similar. For example doing something like this:
will end up in the following error message:
It tells you the exact line number. What's the difference to the other way?