PHP explode function blank array element
Asked Answered
A

2

10

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?

Animalism answered 20/5, 2013 at 19:20 Comment(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 issueHoenack
S
30

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 ).

Scythia answered 20/5, 2013 at 19:23 Comment(0)
P
6

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

Polad answered 22/5, 2013 at 4:43 Comment(4)
This is the correct solution. But my god, that looks like a lot of commas.Castorina
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.Sella
This is a good solution but it does have one potential problem that the accepted answer does not - the empty string returns [''] rather than []Typewrite
The code should be explode(',', trim(',.str,.ppl', ',')) rather than explode(',', trim(',.str,.ppl'), ','). You are passing three parameters to explode.Armand

© 2022 - 2024 — McMap. All rights reserved.