[] operator not supported for strings – PHP

PHP error log - operator not supported

I had a problem with Revolution Slider on a WordPress installation when upgrading to PHP 7.2+. It would generate the error – PHP Fatal error: [] operator not supported for strings in C:[path]\wp-content\plugins\revslider\includes\framework\base-admin.class.php:71

The problem was from the plugin attempting to use the short array push syntax on a string:

$box = array();
$box['title'] = $title;
$box['location'] = $location;
$box['content'] = $content;
$box['draw_function'] = $customDrawFunction;
self::$arrMetaBoxes[] = $box;

The solution was to modify the last line as such:

self::$arrMetaBoxes = $box;

No explosions, so all is well!

Why was the operator not supported?

A discussion on Stack Overflow gave me a nudge in the right direction. The suggestion was that PHP 7 has problems with empty-index array push syntax.

These are ok and work properly in PHP 7+.

$undeclared_variable_name[] = 'value'; // creates an array and adds one entry

$emptyArray = []; // creates an array
$emptyArray[] = 'value'; // pushes in an entry

An attempt to use empty index push on any variable declared as a string, number, object, etc, doesn’t works however. ie

$declaredAsString = '';
$declaredAsString[] = 'value';

$declaredAsNumber = 1;
$declaredAsNumber[] = 'value';

$declaredAsObject = new stdclass();
$declaredAsObject[] = 'value';

Theses examples all fail with a PHP error, which in my case was “[] operator not supported for strings”

For more PHP related posts, check here

2 thoughts on “[] operator not supported for strings – PHP”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.