explode generating an empty element in an array (2)

Hello,
I'm using explode to delimit a string, for example:

case 1: $testString="apple+";
case 2: //$testString = "+apple orange+";
case 3: //$testString = "apple+orange";
$testStringArr = explode("+", $testString);

The output of the size of the three $testStringArr  both are 2, 3 2.

the result of case 3 is fine.

how could i change the code, so that i could get only "apple" incase 1, and get "apple orange" in case 3?

i used :
for ($k=0; $k<sizeof($testStringArr ); $k++){
      if (strlen($testStringArr[$k])==0 ){
       unset($testStringArr[$k]);
   }

---------------------------
This doesn't work for case 2. Is there something I'm missing? Any suggestion ?

Thanks very much for your reply,
lilyyan
lilyyanAsked:
Who is Participating?
 
glcumminsConnect With a Mentor Commented:
You just need to use trim() to cut of any leading or trailing '+':

$testStringArr = explode("+", trim($testString, '+'));

You will then be exploding strings that look like:

case 1: $testString="apple";
case 2: //$testString = "apple orange";
case 3: //$testString = "apple+orange";
0
 
lilyyanAuthor Commented:
Hi, thanks for your reply. It works great!
0
 
lilyyanAuthor Commented:
one more question, after using trim() function, the unset() process is not necessary to be used ?
0
 
glcumminsCommented:
That is entirely up to you. My preference would be to simply call unset() on the entire array when you are finished using it. However, if the strings that you are storing as elements are quite massive, then you may be better off calling unset() on each element as you finish using it.
0
 
lilyyanAuthor Commented:
Hi, thanks very much for your reply. Helpful!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.