• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 192
  • Last Modified:

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
0
lilyyan
Asked:
lilyyan
  • 3
  • 2
1 Solution
 
glcumminsCommented:
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

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now