Your code works fine, it returns 3 as expected, because you have provided right input string to work the code, but problem arise when you assign database field's value to $tags
, because it can also contains empty string as you have said in your question.
so as you have told it can be zero or more than zero tags in db field, so when $tags
contains no tags or empty string then as php explode() function's manual says:
If delimiter contains a value that is not contained in string then array containing string like [ " " ] will be returned.
So when your $tags
contain empty string then explode()
returns array containing empty string, so now your $tagArray=[""]
, after exploding you are using count()
function, so as per php manual of count() It
Returns the number of elements in array_or_countable. When the parameter is neither an array nor an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable is NULL, 0 will be returned.
so because your $tagArray
is not NULL but $tagArray=[""]
, so count($tagArray)
is returning one.
So for solving it use the code below:
$tags = "Videos,Magazines,Store";
// it can also contains empty string like $tags = ""
$arrayCount = ($tags)?count(explode(",",$tags)):0;
//here $arrayCount will have 3 as expected, But if your $tags contains empty string it will return 0 instead of 1.