Disclaimer: I do eventually answer your question, there are just some other things I wished to point out.
GET vs REQUEST
First of all, I would consider using $_GET
instead of $_REQUEST
. I'm assuming its get your using judging by the data you are passing. It is generally a better idea to use the specific array you need if you know it rather than one that could potentially contain data from another source. For example, should you ever create a form with a path input, it will supersede any get path. But this isn't even necessary, the remote user can change that value should they wish. However, if you were to call them separately $_GET[ 'path' ]
and $_POST[ 'path' ]
you will be able to use them both together without losing any information and they are less likely to be hijacked (minus get, its pretty easy to hijack that).
Filter Input
Array Shift
Order of Logic
Instead of checking if the value of $urlSegments
is empty, I would set it first then check it. A couple of reasons for this. What if "path" starts with a forward slash "/"? I believe explode will produce an empty element at the very beginning. Unless this is the desired result, it could cause errors. Also, it removes the need for those magic numbers, i.e.($urlSegments[0]
) Yes its obvious where it came from and why you are using it, but it is a bad habit and is not extendable.
Here's the Better Solution: Only one parameter
EditHere's the Better Solution: Multiple parameters
I just realized that $urlSegments
could very likely be longer than 3 elements. In this case, I would filter and pad it like I did above, shift the first two elements into their respective variables then set $parameters
to whatever remains of $urlSegments
. Padding it first ensures that each variable has a default value of an empty string.
Shorthand
Finally, it is rarely a good idea to use shorthand in PHP. If I did not know what you were trying to accomplish, or had a slightly older version of PHP, I would think that $urlSegments = [];
was syntactically wrong. Yes it works, but you could run across problems in the future. Not to mention its just easier to read $urlSegments = array();
Regex
That should clean up your code considerably. I would hesitate to suggest any regex, mainly because I find it extremely difficult to read.
Edits
Edited a few times to clean up post and add the second "Better Solution".