PHP Array Syntax Parse Error Left Square Bracket "["

PHP Array Syntax Parse Error Left Square Bracket [

You can't use function array dereferencing

return f1(/*some args*/)[0];

until PHP 5.4.0 and above.

Php square brackets syntax error

The first is because the new [] syntax for instantiating arrays only works in 5.4 and above. So, replace it with array():

// 5.4+ only:
array($userName => ['score' => $score]);
// 5.3 (and earlier) and 5.4+
array($userName => array('score' => $score));

The second is a different 5.4 feature, that of accessing arrays returned from functions, where you should use a temporary variable:

// 5.4+ only:
$this->Auth->user()['id']
// 5.3 (and earlier) and 5.4+:
$result = $this->Auth->user()
$result[id]

Or, for preference, upgrade your production server to a PHP version that's a bit more modern than the four-or-five year old version you're using. To save on more of these headaches, you either need to do that or start developing locally in 5.3. (If you need to do the latter, I'd look into virtualising your development setup, so you could develop in a virtual box against 5.3 for older production systems.)

Unexpected bracket '[' - PHP

That's called array dereferencing and only works in PHP 5.4+. You're probably running PHP 5.3.x wherever you are getting that error.

See results based on different PHP versions

PHP parse/syntax errors; and how to solve them

What are the syntax errors?

PHP belongs to the C-style and imperative programming languages. It has rigid grammar rules, which it cannot recover from when encountering misplaced symbols or identifiers. It can't guess your coding intentions.

Function definition syntax abstract

Most important tips

There are a few basic precautions you can always take:

  • Use proper code indentation, or adopt any lofty coding style.
    Readability prevents irregularities.

  • Use an IDE or editor for PHP with syntax highlighting.
    Which also help with parentheses/bracket balancing.

    Expected: semicolon

  • Read the language reference and examples in the manual.
    Twice, to become somewhat proficient.

How to interpret parser errors

A typical syntax error message reads:

Parse error: syntax error, unexpected T_STRING, expecting ';' in file.php on line 217

Which lists the possible location of a syntax mistake. See the mentioned file name and line number.

A moniker such as T_STRING explains which symbol the parser/tokenizer couldn't process finally. This isn't necessarily the cause of the syntax mistake, however.

It's important to look into previous code lines as well. Often syntax errors are just mishaps that happened earlier. The error line number is just where the parser conclusively gave up to process it all.

Solving syntax errors

There are many approaches to narrow down and fix syntax hiccups.

  • Open the mentioned source file. Look at the mentioned code line.

    • For runaway strings and misplaced operators, this is usually where you find the culprit.

    • Read the line left to right and imagine what each symbol does.

  • More regularly you need to look at preceding lines as well.

    • In particular, missing ; semicolons are missing at the previous line ends/statement. (At least from the stylistic viewpoint. )

    • If { code blocks } are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper code indentation to simplify that.

  • Look at the syntax colorization!

    • Strings and variables and constants should all have different colors.

    • Operators +-*/. should be tinted distinct as well. Else they might be in the wrong context.

    • If you see string colorization extend too far or too short, then you have found an unescaped or missing closing " or ' string marker.

    • Having two same-colored punctuation characters next to each other can also mean trouble. Usually, operators are lone if it's not ++, --, or parentheses following an operator. Two strings/identifiers directly following each other are incorrect in most contexts.

  • Whitespace is your friend.
    Follow any coding style.

  • Break up long lines temporarily.

    • You can freely add newlines between operators or constants and strings. The parser will then concretize the line number for parsing errors. Instead of looking at the very lengthy code, you can isolate the missing or misplaced syntax symbol.

    • Split up complex if statements into distinct or nested if conditions.

    • Instead of lengthy math formulas or logic chains, use temporary variables to simplify the code. (More readable = fewer errors.)

    • Add newlines between:

      1. The code you can easily identify as correct,
      2. The parts you're unsure about,
      3. And the lines which the parser complains about.

      Partitioning up long code blocks really helps to locate the origin of syntax errors.

  • Comment out offending code.

    • If you can't isolate the problem source, start to comment out (and thus temporarily remove) blocks of code.

    • As soon as you got rid of the parsing error, you have found the problem source. Look more closely there.

    • Sometimes you want to temporarily remove complete function/method blocks. (In case of unmatched curly braces and wrongly indented code.)

    • When you can't resolve the syntax issue, try to rewrite the commented out sections from scratch.

  • As a newcomer, avoid some of the confusing syntax constructs.

    • The ternary ? : condition operator can compact code and is useful indeed. But it doesn't aid readability in all cases. Prefer plain if statements while unversed.

    • PHP's alternative syntax (if:/elseif:/endif;) is common for templates, but arguably less easy to follow than normal { code } blocks.

  • The most prevalent newcomer mistakes are:

    • Missing semicolons ; for terminating statements/lines.

    • Mismatched string quotes for " or ' and unescaped quotes within.

    • Forgotten operators, in particular for the string . concatenation.

    • Unbalanced ( parentheses ). Count them in the reported line. Are there an equal number of them?

  • Don't forget that solving one syntax problem can uncover the next.

    • If you make one issue go away, but other crops up in some code below, you're mostly on the right path.

    • If after editing a new syntax error crops up in the same line, then your attempted change was possibly a failure. (Not always though.)

  • Restore a backup of previously working code, if you can't fix it.

    • Adopt a source code versioning system. You can always view a diff of the broken and last working version. Which might be enlightening as to what the syntax problem is.

  • Invisible stray Unicode characters: In some cases, you need to use a hexeditor or different editor/viewer on your source. Some problems cannot be found just from looking at your code.

    • Try grep --color -P -n "\[\x80-\xFF\]" file.php as the first measure to find non-ASCII symbols.

    • In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularly can find their way into the source code.

  • Take care of which type of linebreaks are saved in files.

    • PHP just honors \n newlines, not \r carriage returns.

    • Which is occasionally an issue for MacOS users (even on OS  X for misconfigured editors).

    • It often only surfaces as an issue when single-line // or # comments are used. Multiline /*...*/ comments do seldom disturb the parser when linebreaks get ignored.

  • If your syntax error does not transmit over the web:
    It happens that you have a syntax error on your machine. But posting the very same file online does not exhibit it anymore. Which can only mean one of two things:

    • You are looking at the wrong file!

    • Or your code contained invisible stray Unicode (see above).
      You can easily find out: Just copy your code back from the web form into your text editor.

  • Check your PHP version. Not all syntax constructs are available on every server.

    • php -v for the command line interpreter

    • <?php phpinfo(); for the one invoked through the webserver.


    Those aren't necessarily the same. In particular when working with frameworks, you will them to match up.

  • Don't use PHP's reserved keywords as identifiers for functions/methods, classes or constants.

  • Trial-and-error is your last resort.

If all else fails, you can always google your error message. Syntax symbols aren't as easy to search for (Stack Overflow itself is indexed by SymbolHound though). Therefore it may take looking through a few more pages before you find something relevant.

Further guides:

  • PHP Debugging Basics by David Sklar
  • Fixing PHP Errors by Jason McCreary
  • PHP Errors – 10 Common Mistakes by Mario Lurig
  • Common PHP Errors and Solutions
  • How to Troubleshoot and Fix your WordPress Website
  • A Guide To PHP Error Messages For Designers - Smashing Magazine

White screen of death

If your website is just blank, then typically a syntax error is the cause.
Enable their display with:

  • error_reporting = E_ALL
  • display_errors = 1

In your php.ini generally, or via .htaccess for mod_php,
or even .user.ini with FastCGI setups.

Enabling it within the broken script is too late because PHP can't even interpret/run the first line. A quick workaround is crafting a wrapper script, say test.php:

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("./broken-script.php");

Then invoke the failing code by accessing this wrapper script.

It also helps to enable PHP's error_log and look into your webserver's error.log when a script crashes with HTTP 500 responses.

How can [ be an operator in the PHP language specification?

This is a very valid question.

1. Precedence in between [...]

First there is never an ambiguity to what PHP should evaluate first when looking at the
right side of the [, since the bracket requires a closing one to go with it, and so
every operator in between has precedence over the opening bracket.

Example:

$a[1+2]

The + has precedence, i.e. first 1+2 has to be evaluated before PHP can determine which
element to retrieve from $a.

But the operator precedence list is not about this.

2. Associativity

Secondly there is an order of evaluating consecutive pairs of [], like here:

$b[1][2]

PHP will first evaluate $b[1] and then apply [2] to that. This is left-to-right
evaluation and is what is intended with left associativity.

But the question at hand is not so much about associativity, but about precedence with regards to other operators.

3. Precedence over operators on the left side

The list states that clone and new operators have precedence over [, and this is not easy to test.

First of all, most of the constructs where you would combine new with square brackets are considered invalid
syntax. For example, both of these statements:

$a = new myClass()[0];
$a = new myClass[0];

will give a parsing error:

syntax error, unexpected '['

PHP requires you to add parentheses to make the syntax valid. So there is no way we can test
the precedence rules like this.

But there is another way, by using a variable containing a class name:

$a = new $test[0];

This is valid syntax, but now the challenge is to make a class that creates something
that acts like an array.

This is not trivial to do, as an object property is referenced like this: obj->prop, not
like obj["prop"]. One can however use the ArrayObject class which can deal with square brackets. The idea is to extend this class and redefine the offsetGet method to make sure a freshly made object of that class has array elements to return.

To make objects printable, I ended up using the magical method __toString, which is executed when an object needs to be cast to a string.

So I came up with this set-up, defining two similar classes:

class T extends ArrayObject {
public function __toString() {
return "I am a T object";
}
public function offsetGet ($offset) {
return "I am a T object's array element";
}
}

class TestClass extends ArrayObject {
public function __toString() {
return "I am a TestClass object";
}
public function offsetGet ($offset) {
return "I am a TestClass object's array element";
}
}

$test = "TestClass";

With this set-up we can test a few things.

Test 1

echo new $test;

This statement creates a new TestClass instance, which then needs to be converted to
string, so the __toString method is called on that new instance, which returns:

I am a TestClass object

This is as expected.

Test 2

echo (new $test)[0];

Here we start with the same actions, as the parentheses force the new operation to be executed first. This time PHP does not convert the created object to string, but requests array element 0 from it. This request is answered by the offsetGet method, and so the above statement outputs:

I am a TestClass object's array element

Test 3

echo new ($test[0]);

The idea is to force the opposite order of execution. Sadly enough, PHP does not allow this syntax, so will have to break the statement into two in order to get the intended evaluation order:

$name = $test[0];
echo new $name;

So now the [ is executed first, taking the first character of the value of
$test, i.e. "T", and then new is applied to that. That's why I
defined also a T class. The echo calls __toString on that instance, which yields:

I am a T object

Now comes the final test to see which is the order when no parentheses are present:

Test 4

echo new $test[0];

This is valid syntax, and...

4. Conclusion

The output is:

I am a T object

So in fact, PHP applied the [ before the new operator, despite what is stated in the
operator precedence table!

5. Comparing clone with new

The clone operator has similar behaviour in combination with [. Strangely enough, clone and new are not completely equal in terms of syntax rules. Repeating test 2 with clone:

echo (clone $test)[0];

yields a parsing error:

syntax error, unexpected '['

But test 4 repeated with clone shows that [ has precedence over it.

@bishop informed that this reproduces the long standing documentation bug #61513: "clone operator precedence is wrong".

Call array ['items'] not working

my php is PHP Version 5.3.10-1ubuntu3.4

Since PHP 5.4 it's possible:

Source : https://secure.php.net/manual/en/language.types.array.php#example-62

till then

$some_variable = $mastervendor->listvendor();
print_r($some_variable['items']);

On PHP 5.3 or earlier, you have to use a temporary variable.

PHP FastCGI Parse error

I think that the problem is that you can't use function array deferencing, that is the square brackets after a function call. From PHP 5.4 you can. See also this question PHP Array Syntax Parse Error Left Square Bracket "["

So try to assign the result of the function call to a variable, and the use it. Like this:

$response = $fb->api('/me/scores/','GET');
return $response['data'][0]['score'];

Returning arrays in php causes syntax error

This is simply a limitation of PHP's syntax. You cannot index a function's return value if the function returns an array. There's nothing wrong with your function; rather this shows the homebrewed nature of PHP. Like a katamari ball it has grown features and syntax over time in a rather haphazard fashion. It was not thought out from the beginning and this syntactical limitation is evidence of that.

Similarly, even this simpler construct does not work:

// Syntax error
echo array("one", "two", "three")[0];

To workaround it you must assign the result to a variable and then index the variable:

$array = get_arr();
echo $array[0];

Oddly enough they got it right with objects. get_obj()->prop is syntactically valid and works as expected. Go figure.



Related Topics



Leave a reply



Submit