PHP 7.1 Warnings: Illegal String Offset + Cannot Assign Empty String To String Offset (working fine in PHP 7.0 and lower)

Dear fellow reader, please subscribe to our YouTube channel and never miss great future videos! <3

This was a simple question, but googling couldn’t lead me to a clear and proper answer. So, here’s the answer/fix/solution as a personal reminder and potential help to others. I had a strange and annoying problem while updating to PHP 7.1 — everything was working fine, except this little piece of code:

$array = $something; // $something can be anything, another function call, for example, that might return empty/null, array or string
if(!isset($array['id']) ) {
    $array['id'] = '';

Now, this returns PHP warnings under PHP 7.1 (and up):

PHP Warning: Illegal string offset ‘id’ on line 3
PHP Warning: Cannot assign an empty string to a string offset on line 3

Any explanation why?

Answer: Problem is that our variable $array (line #1) is not set or initialized as an array() in case of $something part being undefined in the first place! This was apparently fine in PHP 7.0 and below, but not anymore. Now, PHP will NOT assume or automatically fix our problem any longer, and we need to explicitly set it as array() a priory.

Fixed code version:

$array = (array) $something; // simply cast $variable as array()
if(!isset($array['id']) ) {
    $array['id'] = '';

Hope this helps someone, as the solution is really easy & simple.

PHP Web Development



    1 Comment

    Add Your Comment
  2. 1. Ivan A

    Thanks, this was exactly what we need on an issue today! :D

Post A Comment