Use php to count
- Different ways to write a PHP code
- How to write comments in PHP ?
- Introduction to Codeignitor (PHP)
- How to echo HTML in PHP ?
- Error handling in PHP
- How to show All Errors in PHP ?
- How to Start and Stop a Timer in PHP ?
- How to create default function parameter in PHP?
- How to check if mod_rewrite is enabled in PHP ?
- Web Scraping in PHP Using Simple HTML DOM Parser
- How to pass form variables from one page to other page in PHP ?
- How to display logged in user information in PHP ?
- How to find out where a function is defined using PHP ?
- How to Get $_POST from multiple check-boxes ?
- How to Secure hash and salt for PHP passwords ?
- Program to Insert new item in array on any position in PHP
- PHP append one array to another
- How to delete an Element From an Array in PHP ?
- How to print all the values of an array in PHP ?
- How to perform Array Delete by Value Not Key in PHP ?
- Removing Array Element and Re-Indexing in PHP
- How to count all array elements in PHP ?
- How to insert an item at the beginning of an array in PHP ?
- PHP Check if two arrays contain same elements
- Merge two arrays keeping original keys in PHP
- PHP program to find the maximum and the minimum in array
- How to check a key exists in an array in PHP ?
- PHP | Second most frequent element in an array
- Sort array of objects by object fields in PHP
- PHP | Sort array of strings in natural and standard orders
- How to pass PHP Variables by reference ?
- How to format Phone Numbers in PHP ?
- How to use php serialize() and unserialize() Function
- Implementing callback in PHP
- PHP | Merging two or more arrays using array_merge()
- PHP program to print an arithmetic progression series using inbuilt functions
- How to prevent SQL Injection in PHP ?
- How to extract the user name from the email ID using PHP ?
- How to count rows in MySQL table in PHP ?
- How to parse a CSV File in PHP ?
- How to generate simple random password from a given string using PHP ?
- How to upload images in MySQL using PHP PDO ?
- How to check foreach Loop Key Value in PHP ?
- How to properly Format a Number With Leading Zeros in PHP ?
- How to get a File Extension in PHP ?
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string in PHP ?
PHP count() Function
The count() function returns the number of elements in an array.
Syntax
Parameter Values
- 0 — Default. Does not count all elements of multidimensional arrays
- 1 — Counts the array recursively (counts all the elements of multidimensional arrays)
Technical Details
Return Value: | Returns the number of elements in the array |
---|---|
PHP Version: | 4+ |
PHP Changelog: | The mode parameter was added in PHP 4.2 |
More Examples
Example
Count the array recursively:
echo «Normal count: » . count($cars).»
«;
echo «Recursive count: » . count($cars,1);
?>
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
count
Counts all elements in an array when used with an array. When used with an object that implements the Countable interface, it returns the return value of the method Countable::count() .
Parameters
If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array.
count() can detect recursion to avoid an infinite loop, but will emit an E_WARNING every time it does (in case the array contains itself more than once) and return a count higher than may be expected.
Return Values
Returns the number of elements in value . Prior to PHP 8.0.0, if the parameter was neither an array nor an object that implements the Countable interface, 1 would be returned, unless value was null , in which case 0 would be returned.
Changelog
Version | Description |
---|---|
8.0.0 | count() will now throw TypeError on invalid countable types passed to the value parameter. |
7.2.0 | count() will now yield a warning on invalid countable types passed to the value parameter. |
Examples
Example #1 count() example
$a [ 0 ] = 1 ;
$a [ 1 ] = 3 ;
$a [ 2 ] = 5 ;
var_dump ( count ( $a ));
?php
$b [ 0 ] = 7 ;
$b [ 5 ] = 9 ;
$b [ 10 ] = 11 ;
var_dump ( count ( $b ));
?>
The above example will output:
Example #2 count() non Countable|array example (bad example — don’t do this)
$b [ 0 ] = 7 ;
$b [ 5 ] = 9 ;
$b [ 10 ] = 11 ;
var_dump ( count ( $b ));
?php
The above example will output:
Output of the above example in PHP 7.2:
int(3) Warning: count(): Parameter must be an array or an object that implements Countable in … on line 12 int(0) Warning: count(): Parameter must be an array or an object that implements Countable in … on line 14 int(1)
Output of the above example in PHP 8:
int(3) Fatal error: Uncaught TypeError: count(): Argument #1 ($var) must be of type Countable .. on line 12
Example #3 Recursive count() example
$food = array( ‘fruits’ => array( ‘orange’ , ‘banana’ , ‘apple’ ),
‘veggie’ => array( ‘carrot’ , ‘collard’ , ‘pea’ ));
?php
// recursive count
var_dump ( count ( $food , COUNT_RECURSIVE ));
// normal count
var_dump ( count ( $food ));
The above example will output:
Example #4 Countable object
class CountOfMethods implements Countable
private function someMethod ()
>
?php
public function count (): int
return count ( get_class_methods ( $this ));
>
>
$obj = new CountOfMethods ();
var_dump ( count ( $obj ));
?>
The above example will output:
See Also
- is_array() — Finds whether a variable is an array
- isset() — Determine if a variable is declared and is different than null
- empty() — Determine whether a variable is empty
- strlen() — Get string length
- is_countable() — Verify that the contents of a variable is a countable value
- Arrays
- Array Functions
- array_change_key_case
- array_chunk
- array_column
- 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_is_list
- array_key_exists
- array_key_first
- array_key_last
- array_keys
- array_map
- array_merge_recursive
- array_merge
- array_multisort
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_replace_recursive
- array_replace
- 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
- end
- extract
- in_array
- key_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
- each
count
Подсчитывает количество элементов массива или что-то в объекте.
Для объектов, если у вас включена поддержка SPL, вы можете перехватить count() , реализуя интерфейс Countable. Этот интерфейс имеет ровно один метод, Countable::count() , который возвращает значение функции count() .
Пожалуйста, смотрите раздел «Массивы» в этом руководстве для более детального представления о реализации и использовании массивов в PHP.
Список параметров
Если необязательный параметр mode установлен в COUNT_RECURSIVE (или 1), count() будет рекурсивно подсчитывать количество элементов массива. Это особенно полезно для подсчёта всех элементов многомерных массивов.
count() умеет определять рекурсию для избежания бесконечного цикла, но при каждом обнаружении выводит ошибку уровня E_WARNING (в случае, если массив содержит себя более одного раза) и возвращает большее количество, чем могло бы ожидаться.
Возвращаемые значения
Возвращает количество элементов в array_or_countable . Если параметр не является массивом или объектом, реализующим интерфейс Countable, будет возвращена 1. За одним исключением: если array_or_countable — NULL , то будет возвращён 0.
count() может возвратить 0 для переменных, которые не установлены, но также может возвратить 0 для переменных, которые инициализированы пустым массивом. Используйте функцию isset() для того, чтобы протестировать, установлена ли переменная.
Примеры
Пример #1 Пример использования count()
$a [ 0 ] = 1 ;
$a [ 1 ] = 3 ;
$a [ 2 ] = 5 ;
$result = count ( $a );
// $result == 3?php
$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()
$food = array( ‘fruits’ => array( ‘orange’ , ‘banana’ , ‘apple’ ),
‘veggie’ => array( ‘carrot’ , ‘collard’ , ‘pea’ ));?php
// рекурсивный count
echo count ( $food , COUNT_RECURSIVE ); // выводит 8// обычный count
echo count ( $food ); // выводит 2Смотрите также
- is_array() — Определяет, является ли переменная массивом
- isset() — Определяет, была ли установлена переменная значением отличным от NULL
- strlen() — Возвращает длину строки