PHP explode

Say you store a csv formatted string somewhere to represent an array. For example, Johnny has items “apple|orange|banana”. Then in your code, you may parse out the items as follows:

$items = "apple|orange|banana"; // retrieve it from somewhere
$my_arr = explode("|", $items);
if (count($my_arr) > 0){
  print "Johnny has something.";
}else{
  print "Johnny has nothing.";
}

It works fine as it seems.

Well, actually, you will never see the “Johnny has nothing” print out. Surprisingly, even if $items is an empty string, explode will still return an array with one element. That array is:

Array
(
  [0] =>
)

Sigh… to avoid this, if you have to use the csv format, then add an if statement to double check the string length.

$items = "apple|orange|banana"; // retrieve it from somewhere
if ($items != ""){
  $my_arr = explode("|", $items);
  print "Johnny has something.";
}else{
  print "Johnny has nothing.";
}

Best practice I think is to store such an array in json format. That way you can completely avoid this surprise!

Ref: http://www.php.net/manual/en/function.explode.php#99830

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s