Home » Php » PHP explode function blank array element

PHP explode function blank array element

Posted by: admin July 12, 2020 Leave a comment


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

The string i want to explode is:


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


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?

How to&Answers:

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


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