如何在PHP中计算逗号分隔的值? [英] How do I count comma-separated values in PHP?

查看:216
本文介绍了如何在PHP中计算逗号分隔的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量,其值用逗号(Implode)隔开,并且我试图获取该变量中值的总数.然而. count()仅返回1.

I have a variable holding values separated by a comma (Implode), and I'm trying to get the total count of the values in that variable. However. count() is just returning 1.

我尝试将逗号分隔的值转换为格式正确的数组,该数组仍会溢出.

I've tried converting the comma-separated values to a properly formatted array which still spits out1.

这是sarray会话等于value1,value2,value3的快速代码段:

So here is the quick snippet where the sarray session is equal to value1,value2,value3:

$schools = $_SESSION['sarray'];
$result = count($schools);

推荐答案

您需要爆炸 转换为实际数组:

You need to explode $schools into an actual array:

$schools = $_SESSION['sarray'];
$schools_array = explode(",", $schools);
$result = count($schools_array);

如果您只需要计数,并且100%确保它是一个干净的逗号分隔列表,则还可以使用

if you just need the count, and are 100% sure it's a clean comma separated list, you could also use substr_count() which may be marginally faster and, more importantly, easier on memory with very large sets of data:

$result = substr_count( $_SESSION['sarray'], ",") +1; 
 // add 1 if list is always a,b,c;

这篇关于如何在PHP中计算逗号分隔的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆