I always check others code, most of the times they start array with empty, nothing inside the array, it is just a bracket like $array = array();
Why would we need such kind of process and what is the benefit of using empty array?
I always check others code, most of the times they start array with empty, nothing inside the array, it is just a bracket like $array = array();
Why would we need such kind of process and what is the benefit of using empty array?
A common reason is if a foreach loop is to be working on the contents of an array. If you don’t set up an empty array and nothing gets added to the array then the foreach loop will complain about being given a string to work with when it’s expecting to receive an array to work with
Another reason is when you are using OOP
with MVC
, you typically use Dependacy Injections
. In which case, if the given function is given an empty array, PHP
will complain since the array is empty. So to avoid this, people usually append an empty array before it so that when the dependency gets injected, if the array is empty, the variable gets an empty array. If the array has data, the array gets processed as normal.
The above are great reasons why people do this. When I first start learning programming in the early 80s one of the first things you had to do was declare the variables (usually it was at the top). I believe the reason back then was to reserve memory space for back then memory was a valuable commodity. Needless to say when I started learning PHP (and other languages) I kind of went into a coma for PHP played loose with coding structure.
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.