If you simply want to assign values to a variable this way:$array[]="value 1" and $array[]="value 2"
do you first have to declare $array=array()? Obviously you don't HAVE to, as it works without it, but why would you do that then? Or what is the benefit of doing it?
5 Answers
What you are describing is not a declaration but an initialization. You are not declaring $array is an array, you are assigning it a value (empty array).
Such an initialization can be used to establish a scope, and perhaps it can make the code more readable (although I can't see how), but usually it is only done when you specifically want an empty array. The classic example is when using the [] syntax to append to an array. Consider the following:
$a = 'old value';
$a = array();
$a[] = 1;
$a[] = 2;
$a[] = 3;
Without the second line, this will produce an error.
By the way, The array() command isn't an ordinary function. It's a language construct, and starting with PHP 5.4 you can replace it with the shorter [] syntax:
$a = 'old value';
$a = [];
$a[] = 1;
$a[] = 2;
$a[] = 3;
Comments
It could also be useful when you structure your code. For example If we first declare the variable in the top
<?php
$myArray = array();
//...
And in the bottom we load a template file $template->render('template.html', $myArray);
Let's say we have a if statement and if the certain condition is true we assign a new value to the array. But if the condition was not true we would not pass any information (new value to the array) thus the array would not be initiated - it would generate an error unless the array wasn't declared. But since it is, we would simply just load an empty array and there would be no errors.
1 Comment
end($array) or whatever, even if the array is declared but empty, it would result in an error... so you would have to check for that in any case, no?Mostly for documentative purposes. It reminds the developer that the variable is intended to be used as an array.
As an example, in CodeIgniter, you can pass values to a view, but they must be an array or it throws an exception. Declaring the variable as array() reminds you that even if you intend to pass a single value, you must insert it as an element in the array.
Comments
No you don't.
Generally, the only time I initialize an array with an empty array is in cases like this:
$list = array();
for($database_result as $row)
{
$list[] = $row['value'];
}
echo implode(', ', $list);
If it happened to be no rows in the database result, then the implode call would fail, since $list would not exist.
The example you give, of just setting a list of values you already know, I generally do like this:
$array = array
(
"value 1",
"value 2",
);