tags:

views:

53

answers:

4

Hey folks,

I have a variable holding values separated by a comma (Implode), 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 heres the quick snippet where the sarray session equals to value1,value2,value3:

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

Any help would be appreciated.

+4  A: 

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;
Pekka
Thank you everyone, would vote you guys up--but I'm new here.
Jay
@Jay no problem, you're welcome.
Pekka
@pekka. Voted you up for the options ;) however, for substr_count, it should be +1
Ben
@Ben you're right, edited, cheers!
Pekka
@pekka. Not in the count(), but in the substr_count() example ;)
Ben
@Ben it's time for me to call it a day. :) thanks.
Pekka
+1  A: 
$schools = $_SESSION['sarray'];
$array = explode(',', $schools); array_walk($array, 'trim');
$count = count($array);

The array_walk($array, 'trim') will remove any trailing space in elements value. :)

TiuTalk
A: 

Should be

$result = count(explode(',',$schools));

Ben
+1  A: 

Actually, its simpler than that:

$count = substr_count($schools, ',') + 1;
code_burgar
Forgive me if I'm wrong, but I think you mean `substr_count`, and why -1? Surely +1?
adam
@adam yeah, you are right, I typed the response in a hurry :)
code_burgar
this will work until there is a school with , in name
zerkms