I’m setting the value of the variable as a array.
Based on some conditions I have to initialize wether
array('a', 'b');
or
array('a', 'b', 'c');
So what is the best way?
Should we write
$a = array('a', 'b');
if($b > 0) {
$a[] = 'c'?
}
or
if($b > 0) {
$a = array('a', 'b', 'c');
} else {
$a = array('a', 'b');
}
First one looks more nice for me.
First we should define what is “best”. For me best is:
Both are almost identical compared as speed of execution (I did a quick test with 1mil iterations), so no clear winner here.
Both examples are easy to read, however I’ll stick with the first one, because if for some reason you are requested to add “a1” to the array, you’ll end having to change one line of code, not two.
EDIT: Here is the code I ran ($b = 0 and $b = 1 doesn’t change it much.:
EDIT2: Seems my first benchmark was wrong. Here is a second one doing only one iteration. Clearly the second block of code executes faster.
Output: