Home > Article > Backend Development > Why Am I Getting the \"Fatal Error: [] Operator Not Supported for Strings\" in PHP 7?
Troubleshooting the "Fatal Error: [] Operator Not Supported for Strings" Issue
This fatal error arises when attempting to employ the short syntax for array push operations on a non-array variable, typically a string. Examining the provided code snippet, it's likely that one or more of the variables ($name, $date, $text, $date2) were initially defined as strings.
To correct this issue, alter the assignments within the loop to directly assign row values to these variables without creating arrays:
<code class="php">$name = $row['name']; $date = $row['date']; $text = $row['text']; $date2 = $row['date2'];</code>
PHP 7 has implemented stricter rules for array push syntax with empty indices. Variables that were previously defined as non-arrays (strings, numbers, objects) are now forbidden from using this syntax, leading to the aforementioned error.
To emphasize, these operations remain valid in PHP 7 :
<code class="php">unset($arrayWithEmptyIndices); $arrayWithEmptyIndices[] = 'value'; // Creates an array and adds an entry $array = []; // Creates an array $array[] = 'value'; // Pushes an entry</code>
However, attempts to use array push syntax on variables declared as strings, numbers, or objects will result in a fatal error:
<code class="php">$stringAsVariable = ''; $stringAsVariable[] = 'value'; $numberAsVariable = 1; $numberAsVariable[] = 'value'; $objectAsVariable = new stdclass(); $objectAsVariable[] = 'value';</code>
The above is the detailed content of Why Am I Getting the \"Fatal Error: [] Operator Not Supported for Strings\" in PHP 7?. For more information, please follow other related articles on the PHP Chinese website!