Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Array Functions : count

count

Count elements in an array, or properties in an object (PHP 4, PHP 5)
int count ( mixed var [, int mode] )

Example 299. count() example

<?php
$a
[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3

$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
$result = count($b);
// $result == 3

$result = count(null);
// $result == 0

$result = count(false);
// $result == 1
?>

Example 300.  Recursive count() example (PHP >= 4.2.0)

<?php
$food
= array('fruits' => array('orange', 'banana', 'apple'),
             
'veggie' => array('carrot', 'collard', 'pea'));

// recursive count
echo count($food, COUNT_RECURSIVE); // output 8

// normal count
echo count($food); // output 2

?>

Related Examples ( Source code ) » count
















Code Examples / Notes » count

tom

You can find an average from an array using this and array_sum.
<?php
//array average( array input )
function average($input) {
return array_sum($input) / count($input);
}
?>
You can also do a method of form validation that involves putting all errors into an array and letting count() do the key part.
<?php
if(isset($_POST['submit'])) {
$errors = array();
if(empty($_POST['message'])) $errors[] = "Empty message field";
if(!preg_match('/[a-z0-9.]@[a-z0-9].[a-z]/i', $_POST['email']) {
$errors[] = "Bad email address";
 }
if(count($errors) == 0) {
//process form...
 }
}
?>


david _at_ webgroup _dot_ org

While michael at htmlland dot net's code works, I believe it is better to use:
$extension=substr($file,strrpos($file,".")+1);
This doesn't incur the overhead of array handling.  I haven't tested it for time functions, but it should work just as well and SHOULD be faster.


legobuff

This is taken from sganer@expio.co.nz comments on the sizeof() function:
If some elements in your array are not set, then sizeof() and count() will not return the index of the last element, but will return the number of set elements. To find the index of the last element in the array:
end($yourArray);
$index = key($yourArray);
... Where $yourArray is the array you want to find the last index ($index) of.


moazzam

This is an obvious note, but I am writing it any way so other, who did may not have observed this, can take advantage of it too.
When running loops with count conditions, the code runs faster if you first assign the count() value to a variable and use that (instead of using count() directly in a loop condition.
To explain my point better, here is an example:
<?php
for ($i=0; $i<10000; $i++) {
$arr[] = $i;
}
$time11 = microtime_float();
$bf = "";
for ($i=0; $i<count($arr); $i++) {
$bf .= $arr[$i]."\n";
}
$time12 = microtime_float();
$time1 = $time12 - $time11;
print "First: ".$time1."\n";
$time21 = microtime_float();
$l = count($arr);
for ($i=0; $i<$l; $i++) {
$bf .= $arr[$i]."\n";
}
$time22 = microtime_float();
$time2 = $time22 - $time21;
print "Second: ".$time2."\n";
?>
The output from the code above is (when run many times):
First: 0.13001585006714
Second: 0.099159002304077
First: 0.12128901481628
Second: 0.079941987991333
First: 0.18690299987793
Second: 0.13346600532532
As you can see, the second method (which doesnt use count() directly in the loop) is faster than the first method (which uses count() directly in the loop).
BTW:  I copied the microtime_float() function from one of the comments in the microtime() section. It just returns time with microseconds as float. Check comments in microtime() for more info.


fred d

The trim_text function was helpful, but it did not take account of the possibility of having nothing to trim which can sometimes happen if you are using this function in a loop through data. I've added a count function to deal with that possibility
------------------------------
function trim_text_elipse($text, $count){
//Create variable
$trimmed="";
//Remove double white space
$text = str_replace("  ", " ", $text);
//Turn the text into an array
$string = explode(" ", $text);
//Check to see how many words there are
$wordTotal = count($string);
//Check to see if there are more words than the $count variable
if($wordTotal > $count){
//Loop through adding words until the $count variable is reached
for ( $wordCounter = 0; $wordCounter <= $count; $wordCounter++ ){
$trimmed .= $string[$wordCounter];
//Check to and add space or finish with elipse
if ( $wordCounter < $count ){ $trimmed .= " "; }
else { $trimmed .= " &#8230;"; }
}
}else{
//Set value returned to the existing value
$trimmed =$text;
}
//Trim off any white space
$trimmed = trim($trimmed);
return $trimmed;
}
-------------------------------


wulfson

The last two comments (redbehelit and Jaik) are a little misguided. In a 26 element array,
for ($i = 0; $i < count($arr); $i++) {
works just fine, as count($arr) will return 26, which means that the loop will end as soon as $i gets iterated to 26 (26 < 26 is false). You'd only have to use count($arr) - 1 if your conditional was $i <=
Jaik is correct that it's better not to use count() inside the loop construct. As mentioned in a previous comment, it'd be faster to use
$size = count($arr);
for ($i = 0; $i < $size; $i++) {
I don't agree that foreach should be used instead of this, however. In my trials, I found that using a normal for loop was consistently faster than using a foreach (granted, not a whole lot faster, but everything counts if you're trying to optimize). foreach really ought to only be used when the array you're traversing contains associative indices.


jaik

The last comment is somewhat inefficient as it runs the count() function at the start of every loop.
The preferred way to iterate through an array would be to use the 'foreach' control structure.


martin

The count function does not ignore null values in an array. To achieve this use this function.
<?php
function xcount($array) {
       while (list($key, $value) = each($array)) {
               if ($value) {
                       $count++;
               }
       }
return $count;
}
?>


chopin

sizeof(), count() function is for only array not string data type.
ex) $str = "abcd";
   echo $str[3] ; // string indexing like array
   echo sizeof(str); // return 1 always


simon

Reminder for using count():
<?php
$ary = array(null, "a", "b", null);
echo count($ary);    // count: 4
$ary[10] = "c";
echo count($ary);    // count: 5
$ary[15] = null;
echo count($ary);    // count: 6
?>
=> NULL is seen as an element in count()
Count 2D array:
<?php
$a2Dary = array(array("a", "b") , array(), "v");
echo count($a2Dary);        // count: 3
echo count($a2Dary[0]);    //count 2
echo count($a2Dary[1]);    // count: 0
echo count($a2Dary[2]);    // count: 1
?>
Hope can help you


atoi_monte

Please note: While SPL is compiled into PHP by default starting with PHP 5, the Countable interface is not available until 5.1

09-jul-2002 05:18

Perhaps change the wording of this description from "Count elements in a variable" to "Count total elements in a variable" as it may be interpreted (by me) as a function for counting specific elements (ie, number of substrings)

admin

Note:
print (strlen($a)); // will print 0
$a="";
print (strlen($a)); // will print 1
$a=null;
print (strlen($a)); // will print 1
$a=array();
print (strlen($a)); // will print 0
you can only get an array back to size 0 by using the array() command, not by just setting it to "" or null.


yarolan

NEVER USE IN CYCLES!
//size of $arr ~ 2000 elements
//wrong variant (Time exec ~ 19 sec)
for($i=0;$i<count($arr);$i++)
{
  ...
}
//right variant(Time exec ~ 0.2 sec)
$arr_size=count($arr);
for($i=0;$i<$arr_size;$i++)
{
  ...
}
it was discovered experimentally.


alexandr

My function returns the number of elements in array for multidimensional arrays subject to depth of array. (Almost COUNT_RECURSIVE, but you can point on which depth you want to plunge).
<?
 function getArrCount ($arr, $depth=1) {
  if (!is_array($arr) || !$depth) return 0;

$res=count($arr);

  foreach ($arr as $in_ar)
    $res+=getArrCount($in_ar, $depth-1);
 
  return $res;
 }
?>


bryce

If you're working with a database, you'll probably have much greater luck with: mysql_num_rows( $result );

jmcastagnetto

If you want to disambiguate if a variable contains an array w/ only one element, just us is_array() or gettype()

freefaler

If you want to count only elements in the second level of 2D arrays.A close to mind note, useful for multidimentional arrays:
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
            'veggie' => array('carrot', 'collard','pea'));
// recursive count
echo count($food,COUNT_RECURSIVE);  // output 8
// normal count
echo count($food);                  // output 2
// all the fruits and veggies
echo (count($food,COUNT_RECURSIVE)-count($food,0)); //output 6
?>


michael

I have found on upload scripts or on file manipulation scripts that people can trick a classic file type filter:
example:
$filename="bob.jpg.wav";
$bits= explode(".",$filename);
$extention= $bits[1];
if($extention == "jpg"){ echo"Not correct"; exit; }
This returns the filename extention as jpg not wav.
One way to change this is to use count() :
example:
$filename="bob.jpg.wav";
$bits= explode(".",$filename);
$extention= $bits[count($bits) - 1];
if($extention == "jpg"){ echo"Not correct"; exit; }
This returns the filename extention as wav not jpg.


danny

I actually find the following function more useful when it comes to multidimension arrays when you do not want all levels of the array tree.
// $limit is set to the number of recursions
<?php
function count_recursive ($array, $limit)
{
foreach ($array as $id => $_array)
{
if (is_array ($_array) && $limit > 0) $count += count_recursive ($_array, $limit - 1); else $count += 1;
}
return $count;
}
?>


kanareykin

Here's how to count non-empty elements
in an array of any dimension. Hope
it will be useful for somebody.
<?php
// recursively count all non-empty elements
// in array of any dimension or mixed - i.e.
// array('1' => 2, '2' => array('1' => 3, '2' => 4))
function count_all($arg)
{
// skip if argument is empty
if ($arg) {
// not an array, return 1 (base case)
if(!is_array($arg))
return 1;
// else call recursively for all elements $arg
foreach($arg as $key => $val)
$count += count_all($val);

return $count;
}
}
?>


webmaster

Counting a multi-dimentional array
test array
<?php
$settings[0][0]  = 128;
$settings[0][1]  = 256;
$settings[0][2]  = 384;
$settings[0][3]  = 512;
$settings[0][4]  = 1024;
$settings[0][5]  = 2048;
$settings[1][0]  = 1024;
$settings[1][1]  = 2048;
$settings[1][2]  = 3072;
$settings[1][3]  = 4096;
count($settings) // returns 2
count($settings[0]) // returns 6
count($settings[1]) // returns 4
?>


admin

Be carefull with count when using in a while (list()=each()) construct, count changes the internal array pointer and strange things will happen :-)

dmb27

Be careful of recasting your variables, especially with database array returns:
<?php
$res = mysql_query("select * from blah") // a query that returns an empty set
$row = mysql_fetch_array($res); // get's 0 since there's no return
echo count($row); // echos 1 - since $row is not an array
echo $row[0]; // echos "", but casts $row as an array?
echo count($row); // echos 0 now
?>


scorch

Be careful of recasting your variables, especially with database array returns:
<?php
$res = mysql_query("select * from blah") // a query that returns an empty set
$row = mysql_fetch_array($res); // get's 0 since there's no return
echo count($row); // echos 1 - since $row is not an array
echo $row[0]; // echos "", but casts $row as an array?
echo count($row); // echos 0 now
?>


redbehelit

Be careful if you're using count in a loop. Example:
$arr ends at index number 25 (or $arr[25])
We know there are actually 26 elements when we include element 0 (as we should). This is what count is going to return back. But if we do this:
for ($i = 0; $i < count($arr); i++) {
This loop is going to try to traverse to $arr[26] which does not exist. The last element is at index number 25. We can fix this with a minor edit:
for ($i = 0; $i < count($arr)-1; i++) {


rolandfoxx

As an addition, any of the array manipulation functions can likewise get count to once again return 0:
<?php
$a = array();
print(count($a)); // prints 0
$a[0] = "foo";
array_shift($a);
print(count($a)); //prints 0
$a[0] = "bar";
array_splice($a, 0, 1);
print(count($a)); //prints 0
?>


colin

// countValuesRecursive
// The goal of this function is to count non-false values of a multidimenional array
// This is useful in making a quick determination if a form sent any values
// If no values were sent I can simply return to the blank form rather than continuing to the validation of each input
// There are two limitations of the principle:
// 1. If you WANT to send FALSE, 0, '', or NULL as form values this function will not count those, thus not doing what's expected
// 2. This would create an endless loop on a form that has no required fields such as one where users can choose to recieve optional  email subscriptions but where choosing none is also valid
function countValuesRecursive($array, $count = 0) {

// Cycle through the array
foreach ($array as $value) {

// Check if the value is an array
if (is_array($value)) {

// Cycle through deeper level
$count = countValuesRecursive($value, $count);
}
else {

// Check if the value is TRUE
if ($value) {
$count++;
}
}
}

// Return the count
return $count;
}


07-feb-2002 02:01

<?php
count(false) ==1
?>
this has tripped me up before...


anil dot iitk

<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
            'veggie' => array('carrot', 'collard', 'pea'));
// recursive count
echo "
".count($food, COUNT_RECURSIVE); // output 8
function average($a){
 return array_sum($a)/count($a) ;
}
$b = array(1,2,3,4,5,6,7,8,9);
echo "Average of array:".average($b);
?>


Change Language


Follow Navioo On Twitter
array_change_key_case
array_chunk
array_combine
array_count_values
array_diff_assoc
array_diff_key
array_diff_uassoc
array_diff_ukey
array_diff
array_fill_keys
array_fill
array_filter
array_flip
array_intersect_assoc
array_intersect_key
array_intersect_uassoc
array_intersect_ukey
array_intersect
array_key_exists
array_keys
array_map
array_merge_recursive
array_merge
array_multisort
array_pad
array_pop
array_product
array_push
array_rand
array_reduce
array_reverse
array_search
array_shift
array_slice
array_splice
array_sum
array_udiff_assoc
array_udiff_uassoc
array_udiff
array_uintersect_assoc
array_uintersect_uassoc
array_uintersect
array_unique
array_unshift
array_values
array_walk_recursive
array_walk
array
arsort
asort
compact
count
current
each
end
extract
in_array
key
krsort
ksort
list
natcasesort
natsort
next
pos
prev
range
reset
rsort
shuffle
sizeof
sort
uasort
uksort
usort
eXTReMe Tracker