illegal string offset

Description

String shall use the array syntax, with the square brackets. Then, the index in that syntax must be an integer, or must be cast to integer.

When the index cannot be converted to an integer, this warning is displayed. PHP proceeds to cast the value to integer, and use it. It will often be 0, but not always.

An extended error also appear if the result of the conversion is larger than the length of the string.

Example

<?php
  var_dump(foobar[4foo]);
  // displays 'a' + a warning

  var_dump(foobar[-4foo]);
  // displays 'o' + a warning
?>

Solutions

  • Use a cast operator to make the conversion explicit.

  • Check the type of the index to be integer before using it.

  • Use substr() to access a specific offset.