syntax error, unexpected token “public”, expecting “]”¶
Description¶
Inside the square brackets of an array index, PHP expects an expression identifying the key, followed by the closing ]. public is a reserved word: it can only be used as a visibility modifier, never as the start of an expression, such as an unquoted array key. PHP therefore reports that it was still expecting ] to close the array access.
The same message also appears whenever a previous [ was left unclosed, and a later, unrelated public is the first token that cannot continue the pending index expression.
Example¶
<?php
$arr = [1, 2, 3];
$y = $arr[public];
?>
Solutions¶
Quote the key if a string was intended:
$arr['public'].Use a constant or variable holding the intended key instead of the bare word.
Check that every previous
[in the file has a matching].
Changed Behavior¶
This error may appear following an evolution in behavior, in previous versions. See ` <https://php-changed-behaviors.readthedocs.io/en/latest/behavior/.html>`_.