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 $array variable as array()
if(!isset($array['id']) ) {
$array['id'] = '';
}
Hope this helps someone, as the solution is really easy & simple.