Recent Posts

Showing posts with label offset. Show all posts
Showing posts with label offset. Show all posts

How to solve: Notice: Uninitialized string offset: X

Such errors occur, when you are most likely trying to iterate over a non-existing character as shown in the example below.
Consider you, are trying to show every string from $name each separated by <br />
$name = 'abcde'; 

for ($i=0, $len = strlen($name); $i <= $len; $i++)
{
    echo $name[$i], "\n";
}
The above example will generate (online demo):
a
b
c
d
e

Notice: Uninitialized string offset: 5 in XXX on line X
And, as soon as the script finishes echoing e you'll get the error, because inside the for() loop, you have told php to show you the fifth string character from 'abcde' Which, exists, but since the loop starts to count from 0 and echoes e by the time it reaches to 5, it will throw an offset error.