-1

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];
Farer
  • 25
  • 1
  • 5
  • 1
    FWIW http://php.net/manual/en/function.parse-url.php As for your question. Show how you call that function. – ficuscr Jul 18 '18 at 16:35
  • `<=` should just be `<`. You're acceessing outside the string when you reach the last iteration. – Barmar Jul 18 '18 at 17:18

1 Answers1

0

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.

ficuscr
  • 6,975
  • 2
  • 32
  • 52
  • isset on which variable ? how I can fix it ? – Farer Jul 18 '18 at 16:56
  • Thanks for the update you're magician! The problem is solved, cheers! – Farer Jul 18 '18 at 17:05
  • I cant give you up vote, because I got message "Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score." - but thank you so much anyway ! – Farer Jul 18 '18 at 17:06
  • You should **accept** the answer if it answered your question. – ficuscr Jul 18 '18 at 17:09
  • 1
    have done, thanks! maybe better to be there "thumb up" (like on facebook, hehehe!) – Farer Jul 18 '18 at 17:32