[ Count() returning 1 with comma separated string with explode ]
I have a field that stores tags comma seperated. I'm trying to count the number of items listed.
Let's say I've already pulled the data from the DB, and the $tags variable has the following info:
$tags = "Videos,Magazines,Store";
// First separate tags by commas, put into into array
$tagArray = explode(",",$tags);
// Count how many items are in the array
$arrayCount = count($tagArray);
That always returns "1", regardless if there's an item in the array or not. the $tags variable can have any number of items - from empty, to a single item like "Videos" to multiple items "Videos,Games,Store" etc.
Can someone help me out on what I'm doing wrong?
Answer 1
From PHP manual:
If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.
So, simply - if delimiter is not found in string, explode do nothing. If Your variable contains empty string, count() will return 1. You need NULL value for count() to return 0.
Try this:
$tags = "Videos,Magazines,Store";
// First separate tags by commas, put into into array
$tagArray = ($tags != '')?explode(",",$tags):NULL;
// Count how many items are in the array
$arrayCount = count($tagArray);