Count() 返回 1,并用逗号分隔字符串并爆炸
我有一个存储以逗号分隔的标签的字段。我正在尝试计算列出的项目数量。
假设我已经从数据库中提取了数据,并且 $tags 变量具有以下信息:
$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);
无论数组中是否有项目,它总是返回“1”。 $tags 变量可以有任意数量的项目 - 从空到单个项目(如“视频”)到多个项目“视频、游戏、商店”等。
有人可以帮我解决我做错的事情吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自PHP手册:
如果分隔符包含字符串中不包含的值并且使用负限制,则将返回一个空数组,否则将返回包含字符串的数组。
所以,简单来说 - 如果在字符串中找不到分隔符,则爆炸不执行任何操作。如果您的变量包含空字符串,count() 将返回 1。您需要 NULL 值才能让 count() 返回 0。试试
这个:
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:
您的代码工作正常,它按预期返回 3,因为您提供了正确的输入字符串来运行代码,但是当您将数据库字段的值分配给
时出现问题$tags
,因为它也可以包含空字符串,正如您在问题中所说。正如您所说,数据库字段中可以有零个或多个零个标签,因此当
$tags
不包含标签或空字符串时,则为 php explode() 函数的手册说:因此,当您的
$tags
包含空字符串时,explode()
返回包含空字符串的数组,所以现在您的 < code>$tagArray=[""],爆炸后您正在使用count()
函数,因此按照 count()的php手册因为您的
$tagArray
不是 NULL,而是$tagArray=[""]
,所以count($tagArray)
返回一个.因此,为了解决这个问题,请使用下面的代码:
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:So when your
$tags
contain empty string thenexplode()
returns array containing empty string, so now your$tagArray=[""]
, after exploding you are usingcount()
function, so as per php manual of count() Itso because your
$tagArray
is not NULL but$tagArray=[""]
, socount($tagArray)
is returning one.So for solving it use the code below: