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

Mary-Kate Olsen
Release: 2024-11-01 05:03:27
Original
255 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!