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