Count() returning 1 with comma separated string with explode

眉间皱痕 提交于 2020-02-25 07:23:47

问题


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?


回答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);



回答2:


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.


来源:https://stackoverflow.com/questions/7314420/count-returning-1-with-comma-separated-string-with-explode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!