How to fix Illegal string offset in PHP

The illegal string offset issue happens if we try to access a string as array. Illegal string offset is a common issue that most PHP developers encounter. This issue can be produced in many ways. Lets consider following two scenarios.

CASE 1:

  $countryName = 'United States of America';
  echo $countryName['short'];
The above code will produce following warning:
Warning: Illegal string offset 'short' 

CASE 2:

  $countryNames = array('United States of America');
  foreach ($countryNames as $thisCountry) {
    echo $thisCountry['short'];
  }
Similarly the above code will produce following warning:
Warning: Illegal string offset 'short' 
Illegal string offset can be easily solved using isset function. The solution for both the case are as follows:

Solution CASE 1:

  $countryName = 'United States of America';
  if(isset($countryName['short']))
    echo $countryName['short'];

Solution CASE 2:

  $countryNames = array('United States of America');
  foreach ($countryNames as $thisCountry) {
    if(isset($thisCountry['short']))
     echo $thisCountry['short'];
  }

Comments