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

查看:28
本文介绍了如何计算 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.

我已经尝试将逗号分隔的值转换为格式正确的数组,该数组仍然会输出 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);

推荐答案

你需要explode $schools 到一个实际的数组中:

You need to explode $schools into an actual array:

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

如果您只需要计数,并且 100% 确定它是一个干净的逗号分隔列表,您还可以使用 substr_count() 这可能会稍微快一点,更重要的是,对于非常大的数据集,内存更容易:

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天全站免登陆