PHP Count comma separated items

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

PHP Count comma separated items

Post by cjkeane »

Hi everyone,

I have a column of data in mysql (email attachments) listed like so:
042208-FK/doc67834968.pdf[doc67834968.pdf],doc678349689.pdf[doc678349689.pdf]

is there a way in php to strip off everything prior to and including the forward slash and then count the filenames? In the example above, the count would be 2.

I'm not quite sure how to accomplish that. If anyone has any helpful hints, I'd appreciate it. Thanks.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP Count comma separated items

Post by Celauran »

explode() on comma and count() the resulting array?
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: PHP Count comma separated items

Post by cjkeane »

like so?

$string = $result['Attachments'];
$array = explode(',', $string);
$Attachments = count($array);
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP Count comma separated items

Post by Celauran »

You tell me. Is that not working?
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: PHP Count comma separated items

Post by cjkeane »

not quite. it indicates 0, but there are 2 files in the $result['Attachments']
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP Count comma separated items

Post by Celauran »

Code: Select all

$string = '042208-FK/doc67834968.pdf[doc67834968.pdf],doc678349689.pdf[doc678349689.pdf]';
$array  = explode(',', $string);
$count  = count($array);
var_dump($count);
That gives me 2. Have you checked the value of $result['Attachments']?
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: PHP Count comma separated items

Post by cjkeane »

Yes I have.

I've checked the value in the db and echoed $result['Attachments'] field to the screen, and I do get: 042208-FK/doc67834968.pdf[doc67834968.pdf],doc678349689.pdf[doc678349689.pdf], it's just not displaying the count.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP Count comma separated items

Post by Celauran »

Doesn't make much sense that it should work for me and not for you. What about

Code: Select all

var_dump($result['Attachments']); var_dump($array);
after count()?
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: PHP Count comma separated items

Post by cjkeane »

I figured out where I went wrong. Yes the count works just fine now. Thanks.
Post Reply