Search code examples
phpstringoffset

PHP Notice: Uninitialized string offset


I have an error in my code it says PHP Notice: Uninitialized string offset: 14 on line 9

This is line 9:

while($url[$i]!='/' && $url[$i]!='?' && $i<$len)

What to do to avoid this?

Here is the full code in case you need it:

 function remove_extra_in_url($url)
{
    $extra=array('https://','http://','www.',' ');
    $url=strtolower($url);
    $url=str_replace($extra,'',$url);
    $i=0;
    $site_name='';
    $len=strlen($url);
    while($url[$i]!='/' && $url[$i]!='?' && $i<$len)
    {
        $site_name.=$url[$i];
        $i++;
    }
    return $site_name;
}

Many thanks in advance!


Solution

  • At the last character, it will be checking the character before checking there is a character to test. Moving $i<$len will stop any further checks once this condition is false due to using &&...

    while($i<$len && $url[$i]!='/' && $url[$i]!='?')