Counting items in an array.

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

Counting items in an array.

Post by cjkeane »

hi everyone,

i need to count items in an array but after hours of searching, i thought i'd see if someone could point me in the right direction.

i have a field in a table with items separated by commas. i need to count those items.
$result[$fruits] is referring to a column in a query. Does anyone have any helpful hints? thanks.

Code: Select all

<?php
$items = $result['fruits'];
$items= array($items);
$itemcount= count($items);
?>
Dodon
Forum Commoner
Posts: 64
Joined: Wed Aug 03, 2011 4:11 am
Location: Netherlands

Re: Counting items in an array.

Post by Dodon »

$items = explode(",",$result['fruits']);
$itemcount = sizeof($items);
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: Counting items in an array.

Post by cjkeane »

any other suggestions? that didn't seem to work.
oscardog
Forum Contributor
Posts: 245
Joined: Thu Oct 23, 2008 4:43 pm

Re: Counting items in an array.

Post by oscardog »

Code: Select all

$items = $result['fruits'];
$itemsArr = expode(',', $items);
$itemcount= count($itemsArr );
It's similar to the first suggestion, but it will definitely work.
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: Counting items in an array.

Post by cjkeane »

that does work however when there is a null value in the $result it still displays 1 not 0. is there a way around this?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Counting items in an array.

Post by John Cartwright »

Pass the result of your explode through array_filter() to filter out empty array elements.
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: Counting items in an array.

Post by cjkeane »

i figured it out. thank for you suggestions!
Post Reply