Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP explode function blank array element

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?

like image 221
James Avatar asked May 20 '13 19:05

James


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

like image 182
Nick Andriopoulos Avatar answered Sep 24 '22 17:09

Nick Andriopoulos


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

like image 41
Bhargav Sarvepalli Avatar answered Sep 22 '22 17:09

Bhargav Sarvepalli