syntax error, unexpected token “if”, expecting “]”

Description

If-then commands are standalone commands. They can’t be part of another expression. Here, PHP found the if, while it was expecting another expression.

Then, PHP mentions that it was expecting ]: this usually hints at an unclosed array syntax. In the example here, the previous line holds an unclosed array.

Example

<?php

$a = [1,2,

if ($a == 2) {
    print OK;
}

?>

Solutions

  • Look for the previous opening [ square bracket and check that it is all balanced.

  • Look for all previous openings [ square brackets and check that they are all balanced.