I'm using PHP 7.2.2
I'm not able to understand following paragraph taken from the PHP Manual
Warning Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Only the first character of an assigned string is used. As of PHP 7.1.0, assigning an empty string throws a fatal error. Formerly, it assigned a NULL byte.
I've following doubts/questions in my mind regarding the above paragraph :
Can someone please answer all of my doubts/questions in an easy to understand language with suitable working code example?
This part of the manual is in reference to treating strings as an array of characters.
"out of range" offset means an integer index that is at a position longer than the string itself currently is, e.g. $x = "foo"; $x[10] = 'o';
results in $x
becoming foo o
If a non-integer index value is used, the index value is converted to an integer before the index of the string is accessed, e.g. $x = "foo"; $y = $x[true];
results in $y
taking the value of $x[1]
- o
Illegal offset types are anything that couldn't normally be used as an array offset, e.g. class Foo() {}
- indexing a string with $x[new Foo()];
raises a warning
The first chracter piece means that if you attempt to assign a string to the index of an existing string, only the first character of the assigned string will be used, e.g. $x = "foo"; $x[0] = "hi";
results in $x
becoming hoo
;
Assigning a string a value of empty string at an index now results in an error rather than assigning the "null" byte \0
, e.g. $x[0] = ''
will fatal.