I started developing something more complex that what I did before and I want to do it "by the book" and I've read that notices should be avoided, even if they don't affect the usability.
So I have a function that checks the URL and splits it into multiple parts. I then use it to generate the pages, but I get a notice on the frontpage as there aren't enough parts.
Here's some code to see what I'm talking about:
$slug = getRightURL();
In getRightURL()
I have:
$curURL = $_SERVER['REQUEST_URI'];
$URL = explode('/', $curURL);
return $URL[2];
So when the url is just http://example.com/
the function throws a notice;
I was thinking about adding this:
if(count($URL) > 1) return $URL[1];
But is there a better way to do this?
Just counting doesn't always do the trick as PHP arrays aren't actually arrays (something indexed from 0 to length-1) but maps where you can have all kind of not sequenced strings and numbers as index.
To find out if a particular index exists, use isset().
if(isset($URL[2])) {
return $URL[2];
}
else {
return '';
}
You could also shorten this with the ternary operator like so:
return (isset($URL[2]) ? $URL[2] : '');