9

I'm having a few issues with the php explode function.

The string i want to explode is:

,.stl,.ppl

Currently, i'm using the explode function as such:

explode(',',',.stl,.ppl');

Unfortunately this is problematic, it returns three strings:

array(3) { [0]=> string(0) "" [1]=> string(4) ".stl" [2]=> string(4) ".ppl" }

Why is the first string blank?

The obvious solution is to skip the first element of the array, however, why do i need to do this?

Shouldn't the explode() function automatically remove this blank array, or not even generate it at all?

James
  • 349
  • 1
  • 6
  • 17
  • 1
    You have a leading `,` in the string, so technically, you have three items, the first being blank, so `expldoe` just do what it's your expectation wrong. You might want to use `trim` on the string to trim leading/trailing `,` to address this issue – J0HN May 20 '13 at 19:24

2 Answers2

25

This is normal behavior. You need to understand that the blank string is valid string value, hence PHP returns it.

It's quite helpful for cases where elements might not be there, to retain structure.

If you don't want it, you can simply filter it :

  $array = array_filter( explode(",", $string ));

but do note that this will filter out anything that evaluates to false as well ( eg 0 ).

Nick Andriopoulos
  • 10,313
  • 6
  • 32
  • 56
6

You can also trim the leading ',' in your string explode(',',trim(',.str,.ppl'),',')

  • 2
    This is the correct solution. But my god, that looks like a lot of commas. – moopet Aug 20 '14 at 13:50
  • Yep, the thing to know, for the benefit of others reading this, is that trim() can remove any character(s) you specify from the start and end of the string, not just whitespace. So `trim($foo,'/')` is useful when you need to pull apart the fragments of a URL or file/directory path, for example. – William Turrell Nov 06 '17 at 12:09
  • This is a good solution but it does have one potential problem that the accepted answer does not - the empty string returns `['']` rather than `[]` – hypercrypt Apr 27 '23 at 09:03