explode generating an empty element in an array

Posted on 2007-08-07
Last Modified: 2013-11-05
I'm using explode to delimit a string, for example:

//$testString = apple+orange";
$testStringArr = explode("+", $keywords);

The output of the size of the $testStringArr  both are 2.

Any suggestion is highly appreciated,

Question by:lilyyan
    LVL 24

    Accepted Solution

    This is expected behavior for explode(). If you wish to avoid it, you can use trim() to remove any leading or trailing delimiters:

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

    Author Comment

    well, if i use $testString="apple+"; the twp elemens are "apple" and "". (one empty string)
    LVL 3

    Assisted Solution

    Still, as glcummins said, that is the expected behaviour.  If you want to only split when there is a word following the character, use preg_split

    preg_split("/\\+/", $testString, -1, PREG_NO_EMPTY);

    Featured Post

    What Should I Do With This Threat Intelligence?

    Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

    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…
    I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
    The viewer will learn how to count occurrences of each item in an array.
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

    745 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