Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count comma-separated values in PHP?

Tags:

arrays

php

count

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);
like image 768
Jay Avatar asked Mar 16 '10 22:03

Jay


People also ask

How do I count elements in PHP?

The count() function returns the number of elements in an array.

How do I separate comma separated values in PHP?

Use explode() or preg_split() function to split the string in php with given delimiter. PHP | explode() Function: The explode() function is an inbuilt function in PHP which is used to split a string in different strings.

How do you count commas in a string?

Select the cell you will place the counting result, type the formula =LEN(A2)-LEN(SUBSTITUTE(A2,",","")) (A2 is the cell where you will count the commas) into it, and then drag this cell's AutoFill Handle to the range as you need.


2 Answers

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;
like image 185
Pekka Avatar answered Sep 19 '22 22:09

Pekka


Should be

$result = count(explode(',',$schools));
like image 22
Ben Avatar answered Sep 19 '22 22:09

Ben