explode generating an empty element in an array (2)

Posted on 2007-08-09
Last Modified: 2008-02-20
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 ){

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

Thanks very much for your reply,
Question by:lilyyan
    LVL 24

    Accepted Solution

    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";

    Author Comment

    Hi, thanks for your reply. It works great!

    Author Comment

    one more question, after using trim() function, the unset() process is not necessary to be used ?
    LVL 24

    Expert Comment

    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.

    Author Comment

    Hi, thanks very much for your reply. Helpful!

    Featured Post

    Top 6 Sources for Identifying Threat Actor TTPs

    Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

    Join & Write a Comment

    Both Easy and Powerful How easy is PHP? (  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
    These days socially coordinated efforts have turned into a critical requirement for enterprises.
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
    This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now