user3149569 user3149569 - 1 year ago 92
PHP Question

php - url split up produces an empty 0 index

So i'm creating a php application and is currently working on checking the url.

i am running on the build in development server from php, with the public directory as the root

php -S localhost:8080 -t public/

when i explode the url, i do it like this

$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', rtrim($url, '/'));

but if for example type in the url:


the content of $segments is the following:

echo $segments[0]; // empty,
echo $segments[1]; // index
echo $segments[2]; // test

Why is the first index always there, and empty?


solves the problem, but i would like to know why it occours.

Answer Source

If your URL starts with /, exploding on that character will create an empty item at the beginning (there is nothing before the first separator). In this case, since you're already trimming / at the end with rtrim(), it will be a simple fix: use trim() instead to trim both sides:

$segments = explode('/', trim($url, '/'));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download