Search code examples
phpstringuninitialized-constant

Uninitialized string offset error


Why I am getting uninitialized string error, I can't figure out?

Here is my function:

function show_site_name($url,$lenght)
{
    $name='';
    $i=0;
    $slash=0;
    while($slash<3 && $i<=$lenght)
    {
        if($url[$i]=='/') $slash++;
        if($url[$i]!='/' && $slash==2) $name.=$url[$i];
        $i++;
    }
    return($name);
}

EDITED: I am getting "Uninitialized string offset" error at this two lines here:

    if($url[$i]=='/') $slash++;
    if($url[$i]!='/' && $slash==2) $name.=$url[$i];

Solution

  • The function is rather silly. PHP offers nice native functions for parsing a url. Also, I assume "lenght" is the length of the first argument? Which can of course be derived with strlen.

    show_site_name('http://www.example.com', strlen('http://www.example.com'));
    

    Will result in Uninitialized string offset: 22.

    show_site_name('http://www.example.com', strlen('http://www.example.com')-1);
    

    The above is probably what you want. Option base zero, not one.

    if($url[$i]=='/') $slash++;
    

    The line above is where you exceed the string offset. Bad logic. You can fix the code and avoid it or handle it with isset. Trust your error log.

    UPDATE:

    You can avoid it by passing sane arguments like I showed. Or change it to:

    if (isset($url[$i])) {
        if($url[$i]=='/') $slash++;
    } else {
        return $name;
    }
    

    But again, that is just silly.

    If you insist on doing this, let's call it for learning purposes. Why not do:

    function show_site_name($url)
    {
        $lenght = strlen($url) -1;
        ...
    

    Passing a second argument that can simply be derived from the first argument is not a good approach.