PHP Build a Simple PHP Application Listing Inventory Items Creating the Products Array

Lucas Krause
Lucas Krause
19,924 Points

Why 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
Thomas King
15,197 Points

When 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.

Lucas Krause
Lucas Krause
19,924 Points

Thanks for your response. Is that the only reason? I think the error messages will be very similar. For example doing something like this:

$a=array(
    "ABC"
    "101",
    "Hello ".$b
);

will end up in the following error message:

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ')' in [...] on line 5

It tells you the exact line number. What's the difference to the other way?

Philip Cox
Philip Cox
14,818 Points

You cannot push to an array that does not exist :)

Lucas Krause
Lucas Krause
19,924 Points

Ehm yes, that's correct. But I didn't say that the array doesn't exist. I just said that it's empty. ;)

Philip Cox
Philip Cox
14,818 Points

I 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
Lucas Krause
19,924 Points

Well 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
Philip Cox
14,818 Points

I 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.