downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

current> <compact
[edit] Last updated: Fri, 25 May 2012

view this page in

count

(PHP 4, PHP 5)

count変数に含まれるすべての要素、 あるいはオブジェクトに含まれる何かの数を数える

説明

int count ( mixed $var [, int $mode = COUNT_NORMAL ] )

変数に含まれるすべての要素、 あるいはオブジェクトに含まれる何かの数を数えます。

オブジェクトに対して、もし SPL がインストールされている場合、インターフェイス Countable を実装することで count() にフックすることができます。このインターフェイスには 1 つのメソッド Countable::count() があり、count() 関数に対する値を返します。

配列の実装やPHPでの使用法に関する詳細な説明については、マニュアルの 配列のセクションを参照ください。

パラメータ

var

配列あるいはオブジェクト。

mode

オプションのmode 引数が COUNT_RECURSIVE (または 1) にセットされた場合、count() は再帰的に配列をカウントします。 これは多次元配列の全ての要素をカウントするといった場合に特に有効です。 count() は無限の再帰を検出しません。

返り値

varに含まれる要素の数を返します。 もし var が配列もしくは Countable インターフェイスを実装したオブジェクトではない場合、 1 が返されます。 ひとつ例外があり、varNULL の場合、 0 が返されます。

警告

count() は、セットされていない変数に関して 0 を返しますが、変数が空の配列として初期化されている場合にも 0 を返します。 ある変数がセットされているかどうかを調べるには、 isset() を使用してください。

変更履歴

バージョン 説明
4.2.0 オプションのパラメータ mode が追加されました。

例1 count() の例

<?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
?>

例2 再帰的な count() の例

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

// 再帰的なカウント
echo count($foodCOUNT_RECURSIVE); // output 8

// 通常のカウント
echo count($food); // output 2

?>

参考

  • is_array() - 変数が配列かどうかを検査する
  • isset() - 変数がセットされていること、そして NULL でないことを検査する
  • strlen() - 文字列の長さを得る



current> <compact
[edit] Last updated: Fri, 25 May 2012
 
add a note add a note User Contributed Notes count
carlos56_dal at hotmail dot com 13-Apr-2012 07:40
When use an huge array, it's recommended to set a variable with the size of the array, p.g.

<?php

$array_size
= count($your_array);
for(
$i = 0; $i < $array_size; $i++)
{
 
// Process array data
}
?>
It's quicker than:
<?php
for($i = 0; $i < sizeof($your_array); $i++)
{
 
// Process array data
}
?>
In the first example, run the sizeof function once, however in the second example run n times the sizeof function
nicolas dot grekas+php at gmail dot com 10-Sep-2011 11:29
As of PHP 5.2.6, count() DOES detect infinite recursion.
It triggers a warning when its argument is a recursive array.
mike dot mackintosh at angrystatic dot com 08-Sep-2011 10:31
If you try to do a sizeof or count with an object, it will always return 1 if the object is not null.

You need to type cast the object as an array for it to count correctly.

ex:

<?php
$obj
->foo = 'fu';
$obj->bar = $fooBar();

echo
count($obj); //returns 1

echo count( (array) $obj); // returns 2
?>
gothamxi 07-Mar-2011 10:48
simple random value from array.

<?php
$topic
=array(
   
"UFOs",
   
"Barack Obama",
   
"China",
   
"Christianity",
   
"Communism",
   
"World War II",
   
"Global Warming",
   
"Vegetarianism",
            );

echo (
"What do you think about ".$topic[ rand( 1,count($topic) ) ]."? ");

?>

output-->
What do you think about Global Warming? , etc
pro at developergatsby dot com 15-Jan-2011 02:37
Complexity of count function.

I just tested the complexity of count().
It looks O(1).

Here is the result.

<< counting array with 1 element>>
total time : 0.021ms
start -> end : 100 %

<< counting array with 100000 elements>>
total time : 0.015ms
start -> end : 100 %

Here is the testing code.
mini_bench_to is a function.
<?php

$arr
= array();
$arr[] = "1";

$t['start'] = microtime(true);
$size = count($arr);
$t['end'] = microtime(true);
$str_result_bench = mini_bench_to($t);
echo
$str_result_bench; // string return

$arr = array();
for(
$index = 0; $index < 100000; $index++) {
   
$arr[] = $index;
}
$t['start'] = microtime(true);
$size = count($arr);
$t['end'] = microtime(true);
$str_result_bench=mini_bench_to($t);
echo
$str_result_bench; // string return

?>

<?php
function mini_bench_to($arg_t, $arg_ra=false) {
   
$tttime=round((end($arg_t)-$arg_t['start'])*1000,4);
    if (
$arg_ra) $ar_aff['total_time']=$tttime;
    else
$aff="total time : ".$tttime."ms\n";
   
$prv_cle='start';
   
$prv_val=$arg_t['start'];

    foreach (
$arg_t as $cle=>$val)
    {
        if(
$cle!='start')   
        {
           
$prcnt_t=round(((round(($val-$prv_val)*1000,4)/$tttime)*100),1);
            if (
$arg_ra) $ar_aff[$prv_cle.' -> '.$cle]=$prcnt_t;
           
$aff.=$prv_cle.' -> '.$cle.' : '.$prcnt_t." %\n";
           
$prv_val=$val;
           
$prv_cle=$cle;
        }
    }
    if (
$arg_ra) return $ar_aff;
    return
$aff;
}
?>
marc at example dot com 23-Sep-2010 12:10
Just found use for this function...
Can count an array of items where a certain condition is met.
Feel free to improve it.

function countWhere($input = 1, $operator = '==', $where = 1)
{
    $input = is_array($input) ? $input : (array)$input;
    $operator = !in_array($operator, array('<','>','<=', '>=','==', '!=')) ? '==' : $operator;

    $i = 0;

    foreach($input as $current)
    {
        $match = null;
        eval('$match = (bool)("'.$current.'"'.$operator.'"'.$where.'");');

        $i = $match ? $i+1 : $i;
    }

    return $i;
}

USAGE:
echo countWhere(array('PZ','AB','CD','EF','GH'), '!=', 'GH');

OUTPUT:
4
marc at gutt dot it 07-Jun-2010 11:10
There was a change in a PHP5 version. Now an empty string returns 1:
<?php
echo count(''); // returns 1
echo count(array()); // returns 0
?>

This wasn't in PHP4 and some older PHP5 versions.
D X 03-Mar-2010 06:42
To know how much properties an object has, I do it like this:
count((array) $object)
... because count($object) gives me allways 1
ravenswd at gmail dot com 04-Aug-2009 12:37
The code snippet posted by legobuff at hotmail dot com on 02-Feb-2000 contains an error. This is the code that was posted:

<?php
// To find the index of the last element in the array:
end($yourArray);
$index = key($yourArray);
?>

However, this will fail if the indices have been stored out of sequence. What you actually want is max(array_keys($yourArray)), as indicated below:

<?php
$yourArray
= array(1=>'a', 7=>'b', 5=>'c');

print
count($yourArray); // prints 3

end($yourArray);
print
key($yourArray); // prints 5

print max(array_keys($yourArray)); // prints 7
?>
jezdec at email dot cz 19-Apr-2009 04:42
Hi there,
there is a simple script with example for counting rows and columns of a two-dimensional array.

<?php
$data
= array(
   
"apples" =>
        array(
"red", "yellow", "pineapples"),
   
"bananas" =>
        array(
"small", "medium", "big"),
   
"vegs" =>
        array(
"potatoes", "carrots", "onions")
);

$rows = count($data,0);
$cols = (count($data,1)/count($data,0))-1;
print
"There are {$rows} rows and {$cols} columns in the table!";
?>
ceo at l-i-e dot com 17-Dec-2008 12:22
count('') returns the very un-intuitive value of 1...
michael.debyl at gmail dot comz0r 16-Jul-2008 03:45
There doesn't seem to be a succinct method already noted on this page for counting multidimensional array end nodes (Items in multidimensional arrays), so I thought this function might help somebody.

Nice and simple :)

<?php
function rcount ($array) {
 
$count = 0;
  if (
is_array($array)) {
    foreach(
$array as $id=>$sub) {
    if (!
is_array($sub)) { $count++; }
     else {
$count = ($count + rcount($sub)); }
    }
    return
$count;
  }
  return
FALSE;
}
?>
analpaper{gmail} 03-Jul-2008 07:37
I found useful this little function that detects if a array is multidimensional or not.

<?php
function array_is2D($array) {
  return
is_array($array) ? count($array)===count($array, COUNT_RECURSIVE) : -1;
}
?>

---
live2code
Anonymous 11-Jan-2008 01:20
Here is an iterative soloution of danny's count_recursive function which might be more efficient due to the missing recursion

<?php
/**
 * counts elements of an multidimensional array
 *
 * @param array $array Input Array
 * @param int $limit dimensions that shall be considered (-1 means no limit )
 * @return int counted elements
 */
function multicount ($array, $limit = -1)
{
  
$cnt = 0;
  
$limit = $limit > 0 ? (int) $limit : -1;
  
$arrs[] = $array;
   for (
$i=0; isset($arrs[$i]) && is_array($arrs[$i]); ++$i)
   {
      foreach (
$arrs[$i] as $value)
      {
         if (!
is_array($value) ) ++$cnt;
         elseif(
$limit==-1 || $limit>1 )
         {
            if(
$limit>1 ) --$limit;
           
$arrs[] = $value;
         }
      }
   }     
   return
$cnt;
}
?>
atoi_monte at hotmail dot com 28-Jun-2007 02:10
Please note: While SPL is compiled into PHP by default starting with PHP 5, the Countable interface is not available until 5.1
danny at dannymendel dot com 13-Jun-2007 01:14
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;
}
?>
yarolan at mail dot ru 26-Apr-2007 04:56
NEVER USE IN CYCLES!

<?php
//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.
Colin 03-Feb-2007 07:24
<?php
// 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;
    }
?>
alexandr at vladykin dot pp dot ru 08-Nov-2006 04:28
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).

<?php
 
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;
  }
?>
anil dot iitk at gmail dot com 26-Jan-2006 12:32
<?php
$food
= array('fruits' => array('orange', 'banana', 'apple'),
            
'veggie' => array('carrot', 'collard', 'pea'));

// recursive count
echo "<br>".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);

?>
Scorch at netpix dot com 20-Dec-2005 05:59
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
?>
Tom 30-Nov-2005 04:57
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...
 
}
}
?>
Fred D 18-Oct-2005 09:16
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

<?php
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;
}

?>
david _at_ webgroup _dot_ org 12-Feb-2005 04:30
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.
freefaler at gmail dot com 19-Nov-2004 05:01
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
?>
moazzam at ummah dot org 14-Oct-2004 04:59
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.
michael at htmlland dot net 04-Jun-2004 10:30
I have found on upload scripts or on file manipulation scripts that people can trick a classic file type filter:
example:

<?php
$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:

<?php
$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.
rolandfoxx at yahoo dot com 30-Mar-2004 04:13
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
?>
admin at lft-muenchen dot de 12-Mar-2003 04:18
Note:

<?php
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.
simon at invalid dot com 20-Aug-2002 12:40
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
webmaster at NOSPAMtrafficg dot com 26-Apr-2002 03:48
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
?>
kanareykin at denison dot edu 26-Mar-2001 01:13
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;       
    }
}
?>
martin at complinet dot com 30-Nov-2000 04:31
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;
}
?>
jmcastagnetto at php dot net 04-Sep-2000 12:30
If you want to disambiguate if a variable contains an array w/ only one element, just us is_array() or gettype()
legobuff at hotmail dot com 02-Feb-2000 10:43
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.

 
show source | credits | sitemap | contact | advertising | mirror sites