시소당
count
(PHP 3, PHP 4 , PHP 5)
count -- 변수의 원소 갯수를 구한다
설명
int count ( mixed var [, int mode])
일반적으로 array 인 var 안의 원소 갯수를 반환한다. (그외의 것은 한개의 원소를 갖기 때문이다)
var 가 배열이 아니면, 1 을 반환한다 (예외: count(NULL) 는 0과 같다).
참고: 선택적인 mode 매개변수는 PHP 4.2.0부터 사용가능하다.
선택적인 mode 매개변수가 COUNT_RECURSIVE (또는 1)으로 설정되면, count() 는 재귀적으로 배열을 카운트한다. 이 매개변수는 특별히 다차원 배열의 모든 원소를 셀때 유용하다. mode의 기본값은 0이다.
경고
count()는 설정되지 않은 배열에 대해서 0을 반환할것이나, 빈 배열로 초기화된 변수에 대해서도 0을 반환할것이다. 변수가 설정되었는지 확인하기 위해서 isset()을 사용한다.
PHP에서 배열이 어떻게 구현되고 어떻게 사용되는지에 대한 자세한 설명을 보기 위해서 배열 섹션을 참고한다.
예 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;
?>
예 2. 재귀적인 count() 예제코드(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
?>
참고: sizeof() 함수는 count()에 대한 별칭 이다.
is_array(), isset(), strlen() 참고.
add a note User Contributed Notes
count
david _at_ webgroup _dot_ org
12-Feb-2005 07: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 08: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 07: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 01:30
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.
rolandfoxx at yahoo dot com
30-Mar-2004 07: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 07:18
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.
simon at invalid dot com
20-Aug-2002 03: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
bryce at obviously dot com
22-Jul-2002 06:44
If you're working with a database, you'll probably have much greater luck with: mysql_num_rows(
$result );
09-Jul-2002 12: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)
webmaster at NOSPAMtrafficg dot com
26-Apr-2002 06: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
?>
markis dot brachel at ntlworld dot com
12-Apr-2002 08:25
Someone said you couldn't use the for loop and count array command for processing arrays with missing entries.
Well, heres my working idea:
<?
// Set up the array
$holes = array ("first", 2 => "second", 5 => "fifth", "sixth");
// Note blank entries 3 and 4
//count number of entries, this time its 4
$array_count = count(
$holes);
for(
$y=0;
$y<
$array_count;
$y++) {
if(isset(
$holes[
$y])) {
echo(
$holes[
$y]);
}
else {
$array_count++; }
}
// In the middle, check where array entry exists
// If not, then increase the size of array_count
// to reflect gaps in array.
?>
07-Feb-2002 09:01
<?php
count(false) ==1
?>
this has tripped me up before...
kanareykin at denison dot edu
26-Mar-2001 04: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 07: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;
}
?>
admin at serverbase dot com
03-Oct-2000 02:24
Be carefull with count when using in a while (list()=each()) construct, count changes the internal array pointer and strange things will happen :-)
jmcastagnetto at php dot net
04-Sep-2000 03: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 01: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.
chopin at csone dot kaist dot ac dot kr
25-Aug-1999 06:13
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
dmb27 at cornell dot edu
30-Jun-1999 04:53
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
?>