[
These days, the unexpected [
array bracket is commonly seen on outdated PHP versions. The short array syntax is available since PHP >= 5.4. Older installations only support array()
.
$php53 = array(1, 2, 3);
$php54 = [1, 2, 3];
?
Array function result dereferencing is likewise not available for older PHP versions:
$result = get_whatever()["key"];
?
Reference - What does this error mean in PHP? - "Syntax error, unexpected \[
" shows the most common and practical workarounds.
Though, you're always better off just upgrading your PHP installation. For shared webhosting plans, first research if e.g. SetHandler php56-fcgi
can be used to enable a newer runtime.
See also:
BTW, there are also preprocessors and PHP 5.4 syntax down-converters if you're really clingy with older + slower PHP versions.
Other causes for Unexpected [
syntax errors
If it's not the PHP version mismatch, then it's oftentimes a plain typo or newcomer syntax mistake:
You can't use array property declarations/expressions in classes, not even in PHP 7.
protected $var["x"] = "Nope";
?
Confusing [
with opening curly braces {
or parentheses (
is a common oversight.
foreach [$a as $b)
?
Or even:
function foobar[$a, $b, $c] {
?
Or trying to dereference constants (before PHP 5.6) as arrays:
$var = const[123];
?
At least PHP interprets that const
as a constant name.
If you meant to access an array variable (which is the typical cause here), then add the leading $
sigil - so it becomes a $varname
.
You are trying to use the global
keyword on a member of an associative array. This is not valid syntax:
global $var['key'];
]
closing square bracketThis is somewhat rarer, but there are also syntax accidents with the terminating array ]
bracket.
Again mismatches with )
parentheses or }
curly braces are common:
function foobar($a, $b, $c] {
?
Or trying to end an array where there isn't one:
$var = 2];
Which often occurs in multi-line and nested array declarations.
$array = [1,[2,3],4,[5,6[7,[8],[9,10]],11],12]],15];
?
If so, use your IDE for bracket matching to find any premature ]
array closure. At the very least use more spacing and newlines to narrow it down.