0

This might seem trivial but it's hurting my head. Can someone explain the reason The http://php.net/manual/es/function.explode.php examples show (which I have trimmed).

$pizza  = "piece1 piece2 piece3"; // string
$pieces = explode(" ", $pizza);
// after a var dump
array(3) {  [0]=> string(6) "piece1" 
            [1]=> string(6) "piece2" 
            [2]=> string(6) "piece3" }

This works lovely, removes all the spaces and does a nice little array to work with, however when I use something similar shown below

$path = "/test-gallery/2/"; // string
$urlpieces = explode("/", $path);
// after a var dump
array(4) {  [0]=> string(0) "" 
            [1]=> string(12) "test-gallery" 
            [2]=> string(1) "2" 
            [3]=> string(0) "" }

I get the first and last with an empty string. Why does it not remove the first and the last array elements? I can always add another step and remove it but the explode should take it all out shouldnt it?

Thanks for the advice in advance.

4
  • 2
    because this is how explode works!!! Commented Feb 8, 2014 at 5:41
  • 1
    use trim($path,"/"); before explode Commented Feb 8, 2014 at 5:41
  • 1
    As per the doc,each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter. Commented Feb 8, 2014 at 5:41
  • read explode() manual here in2.php.net/explode Commented Feb 8, 2014 at 5:44

1 Answer 1

6

I can always add another step and remove it but the explode should take it all out shouldnt it?

No. that is how explode works. Delimiter is at both end so "" string was found at both the ends after exploding

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the advice, as I mentioned it's probably a trivial question.
:) at least not now. Anyways I added $urlpieces = array_filter($urlpieces); Which did the job

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.