Page 1 of 1

Counting items in an array.

Posted: Thu Aug 11, 2011 4:23 am
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);
?>

Re: Counting items in an array.

Posted: Thu Aug 11, 2011 4:53 am
by Dodon
$items = explode(",",$result['fruits']);
$itemcount = sizeof($items);

Re: Counting items in an array.

Posted: Thu Aug 11, 2011 1:15 pm
by cjkeane
any other suggestions? that didn't seem to work.

Re: Counting items in an array.

Posted: Thu Aug 11, 2011 2:08 pm
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.

Re: Counting items in an array.

Posted: Thu Aug 11, 2011 2:28 pm
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?

Re: Counting items in an array.

Posted: Thu Aug 11, 2011 2:39 pm
by John Cartwright
Pass the result of your explode through array_filter() to filter out empty array elements.

Re: Counting items in an array.

Posted: Thu Aug 11, 2011 5:07 pm
by cjkeane
i figured it out. thank for you suggestions!