Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

arrays - How do I count comma-separated values in PHP?

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.

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

$schools = $_SESSION['sarray'];
$result = count($schools);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to explode $schools into an actual array:

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

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...