Home  >  Article  >  Backend Development  >  Why Am I Getting the \"Fatal Error: [] Operator Not Supported for Strings\" in PHP 7?

Why Am I Getting the \"Fatal Error: [] Operator Not Supported for Strings\" in PHP 7?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 05:03:27256browse

Why Am I Getting the

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP 8.3 Beta ReleasedNext article:PHP 8.3 Beta Released