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

search for in the

current> <compact
[edit] Last updated: Sat, 07 Jan 2012

view this page in

count

(PHP 4, PHP 5)

count배열의 모든 원소나, 객체의 프로퍼티 수를 셉니다

설명

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

배열의 모든 원소나, 객체의 프로퍼티 수를 셉니다.

객체는 SPL을 설치했다면, Countable 인터페이스를 가질 경우에 count()를 사용할 수 있습니다. 이 인터페이스는 정확히 하나의 메쏘드 count()을 가지며, count() 함수의 반환값을 반환합니다.

매뉴얼 배열 섹션을 참고하여 배열이 PHP에서 어떻게 구현되고 사용되는지 확인하십시오.

인수

var

배열.

mode

선택적인 mode 인수를 COUNT_RECURSIVE(또는 1)로 설정하면, count()는 배열을 재귀적으로 셉니다. 이는 다차원 배열의 원소를 셀 경우 유용한 경우가 있습니다. mode 기본값은 0입니다. count()는 무한 재귀를 검출하지 못합니다.

반환값

var 안에 있는 원소 수를 반환합니다. 보통 array이며, 다른 자료형은 하나의 요소만 가집니다.

var가 배열이나 Countable 인터페이스를 가진 객체가 아니라면, 1을 반환합니다. 한가지 예외는, varNULL일 경우에 0을 반환합니다.

Caution

count()는 설정하지 않은 변수에 대하여 0을 반환하지만, 빈 배열에 대해서도 0을 반환합니다. 변수를 설정했는지 여부는 isset()을 사용하시오.

버전 설명
4.2.0 선택적인 mode 인수가 추가되었습니다.

예제

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

Example #2 재귀적인 count() 예제

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

// 재귀 count
echo count($food,COUNT_RECURSIVE);  // 8 출력

// 보통 count
echo count($food);                  // 2 출력

?>

참고

  • is_array() - 변수가 배열인지 확인
  • isset() - 설정된 변수인지 확인
  • strlen() - 문자열 길이를 얻습니다



current> <compact
[edit] Last updated: Sat, 07 Jan 2012
 
add a note add a note User Contributed Notes count - [6 notes]
up
8
danny at dannymendel dot com
5 years ago
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) {
   
$count = 0;
    foreach (
$array as $id => $_array) {
        if (
is_array ($_array) && $limit > 0) {
           
$count += count_recursive ($_array, $limit - 1);
        } else {
           
$count += 1;
        }
    }
    return
$count;
}
?>
up
7
alexandr at vladykin dot pp dot ru
6 years ago
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;
  }
?>
up
1
atoi_monte at hotmail dot com
5 years ago
Please note: While SPL is compiled into PHP by default starting with PHP 5, the Countable interface is not available until 5.1
up
-7
jezdec at email dot cz
4 years ago
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!";
?>
up
-20
nicolas dot grekas+php at gmail dot com
1 year ago
As of PHP 5.2.6, count() DOES detect infinite recursion.
It triggers a warning when its argument is a recursive array.
up
-20
freefaler at gmail dot com
8 years ago
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
?>

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