如何在PHP中计算逗号分隔的值? [英] How do I count comma-separated values in 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屋!