I want to output an array key which get returned from a function. Currently its like this:
$x = explode('/', 'my/path/home');
echo $x[1];
but how can i output with just one line without the variable assignment?
I'm trying this, but it doesnt work:
echo explode('/', 'my/path/home')[1];
If you must do this in one line, IMO it is preferable to use list
:
list(, $x) = explode('/', $path);
This is arguably better than the long-winded
$x = implode('', array_slice(explode('/', $path), 1, 1));
in which it's easy to forget what you were supposed to be doing in the first place.
If you are not sure if there will be a second element, you can guard against problems with
list(, $x) = array_pad(explode('/', $path), 2, null);
However, I don't really recommend any of the above for real code. Use the two-liner if you have to; it will still be easier to read than any of these solutions.
Haven't tried but this may help you:
echo array_slice(explode('/', 'my/path/home'), 1, 1);
Also, this code would explode if there's no slash in the string.
If you really want a one liner for wathever the reason and your PHP version < 5.4, you could just create a function for that :
function getPath($fullPath) {
$x = explode('/', $fullPath);
return $x[1];
}
//now the one-liner
echo getPath('my/path/home');