Reputation: 25
I have a function that explodes a URL into directories. If I visit this script at example.com/test/directory
, it should return test
function URLPart($part) {
if ($part > 0) {
$url = explode("/", $_SERVER['PHP_SELF']);
return $url[$part - 1];
} else {
return $_SERVER['PHP_SELF'];
}
}
URLPart(1);
Why is this not happening? I get nothing!
Upvotes: 2
Views: 31
Reputation: 47854
There are two reasons you get nothing:
Because a function call doesn't print to screen -- echo
does. You need to echo your return
value.
@Syscall is correct that there is a leading /
with $_SERVER['PHP_SELF']
so that is also throwing off your element targeting. 1 - 1
will have you accessing the 0
element explode()
's array. (I'm actually not sure why you were subtracting 1 from $part
.)
While I am here I'll offer some additional advice.
$part
is expected to be an integer, but let's force that to be true with intval()
.!$part
is used in the conditional to determine if the value is 0
$part+3
as the 3rd parameter of the explode()
call so that the function doesn't have to do any unnecessary work. For this case, we are accessing element 2
of the array, so jamming the remainder of the path into element 3
is of no consequence. (see demo's output for how this works out)!isset()
condition.++$part
means add one to $part
.echo
the return value.Code: (Demo)
function URLPart($part){
if(!$part=intval($part)){ // convert to integer and check if zero
return '/example.com/test/directory/foo/bar/what'; // $_SERVER['PHP_SELF']
}else{
$url = explode("/",'/example.com/test/directory/foo/bar/what',$part+3); // $_SERVER['PHP_SELF']
var_export($url);
echo "\n\n";
// when $part=1, offset 2 is desired
if(!isset($url[++$part])){ // if incremented $part is an invalid / non-existent offset
return '/example.com/test/directory/foo/bar/what'; // change this to your needs
}else{
return $url[$part];
}
}
}
echo URLPart(1); // you must echo the return value if you want it to be printed to screen
Output:
array (
0 => '',
1 => 'example.com',
2 => 'test',
3 => 'directory/foo/bar/what',
)
test
Upvotes: 0
Reputation: 19780
The $_SERVER['PHP_SELF']
variable contains an initial /
, e.g. "/test/directory"
.
You have to ltrim($_SERVER['PHP_SELF'],'/')
, before.
$url = explode("/", ltrim($_SERVER['PHP_SELF'], '/'));
or just :
return $url[$part];
Upvotes: 1