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
How can I count the total number of built-in functions in PHP?
Solution 1: You could use a core function to count the number of functions available in the core and installed extensions: Solution 2: Count them here: Solution 3: There are listed function here at PHP website Solution 4:PHP site shows a total of 5368 functions. If passed without any additional parameters, returns the number of array keys on the first level.
How can I count the total number of built-in functions in PHP?
How can I count the total number of built-in functions in PHP, latest version?
You could use a core function to count the number of functions available in the core and installed extensions:
$funcs = get_defined_functions(); echo count($funcs['internal']);
PHP Function List
Here is a list of all the documented PHP functions. Click on any one of them to jump to that page in the manual.
There are 5845 listed function here at PHP website
PHP site shows a total of 5368 functions.
PHP Math Functions, PHP Math Functions ; log10(), Returns the base-10 logarithm of a number ; log1p(), Returns log(1+number) ; max(), Returns the highest value in an array, or the
Count the number of numeric keys in an array
I’m using PHP 5.6, and I have the following array:
Array ( [0] => Array ( [id] => 1 [name] => James ) [1] => Array ( [id] => 2 [name] => Tim [children] => Array ( [0] => Array ( [id] => 4 [name] => Sam ) [1] => Array ( [id] => 5 [name] => Florence ) ) ) [2] => Array ( [id] => 3 [name] => Stephen ) )
I’m trying to find a neat and fast way to count the number of people, which is the same as counting the number of numeric keys, which should be 5 .
echo count($myarray); // 3 (only first level) echo count($myarray, COUNT_RECURSIVE); // 16 (every key/value)
Is there a good way to do this with built-in PHP functions, or do I need to traverse the whole multidimensional array and count them manually.
EDIT My array could end up being 1,000+ people (or more), with many many levels (an unknown number of levels).
It is important to note that, even if there were a PHP built-in (such as count($myarray, COUNT_RECURSIVE_NUMERIC); ) internally, it would still be traversing the whole array, recursively. If you are worried about Out Of Memory errors, try pass-by-reference, which will not copy the array or the array items:
define('COUNT_RECURSIVE', 1); function count_numeric_keys(&$array, $flags = 0) < $count = 0; foreach ($array as $key =>$value) < $count += (int) (is_numeric($key)); if ($flags & COUNT_RECURSIVE && is_array($value)) < $count += count_numeric_keys($value, $flags); >> return (int) $count; > $count = count_numeric_keys($array, COUNT_RECURSIVE);
Comparison with non-pass-by-reference, type-hint, and small benchmark:
define('COUNT_RECURSIVE', 1); function count_numeric_keys(Array &$array, $flags = 0) < $count = 0; foreach ($array as $key =>$value) < $count += (int) (is_numeric($key)); if ($flags & COUNT_RECURSIVE && is_array($value)) < $count += count_numeric_keys($value, $flags); >> return (int) $count; > function count_numeric_keys_np(Array $array, $flags = 0) < $count = 0; foreach ($array as $key =>$value) < $count += (int) (is_numeric($key)); if ($flags & COUNT_RECURSIVE && is_array($value)) < $count += count_numeric_keys_np($value, $flags); >> return (int) $count; > $tpl_array = array( 1=>"one", "two"=>"two", 3=>array( 1=>1, "two"=>2 ) ); // Fill the array with both numeric and non-numeric $array = array(); for($i = 1000; $i > 0; $i--) < $array[] = $tpl_array; >for($i = 1000; $i > 0; $i--) < $array["not a number $i"] = $tpl_array; >echo "Pre Memory: ".memory_get_usage(TRUE).PHP_EOL; echo "Count: ".count_numeric_keys($array, COUNT_RECURSIVE).PHP_EOL; echo "Reference Memory: ".memory_get_usage(TRUE)." current, ".memory_get_peak_usage(TRUE)." peak.\n"; count_numeric_keys_np($array, COUNT_RECURSIVE); echo "No-Reference Memory: ".memory_get_usage(TRUE)." current, ".memory_get_peak_usage(TRUE)." peak.\n";
ODDLY, having a reference on $value , like foreach($array as $key => &value) <> actually increased memory usage. Bizarre.
I just created this recursive function to do this for ya 😛
function countNumericKeys($array) < $count = 0; foreach ($array as $key =>$value) < if (is_numeric($key)) < $count ++; >if (is_array($value)) < $count += countNumericKeys($value); >> return $count; > // Test it! $array = [ 1=>"one", "two"=>"two", 3=>[ 1=>1, "two"=>2 ] ]; print countNumericKeys($array); // Output: 3, correct (in this case at least)!
Shortened the code so it uses ternary operators instead of the if s that it was 😛
function simpleCountNumericKeys($array) < $count = 0; foreach ($array as $key =>$value) < $count += is_numeric($key) ? 1 : 0; $count += is_array($value) ? simpleCountNumericKeys($value) : 0; >return $count; >
TEST USING array_keys — only gets the top level keys of the array
function countArrayKeysNumeric($array) < $count = 0; $keys = array_keys($array); foreach ($keys as $key) $count += is_numeric($key) ? 1 :0; return $count; >$array = [ 1=>"one", "two"=>"two", 3=>[ 1=>1, "two"=>2 ] ]; print countArrayKeysNumeric($array);
PHP sizeof() Function, PHP sizeof() Function · 0: It is the default, does not count all elements of multidimensional arrays · 1: It Counts the array recursively (counts
PHP substring count function
I need to count the number of keyword appearances in a paragraph using php function, have the following code but it won’t run so I must be missing something.
EDIT: I have changed to function to the following based on some feedback here:
I have the following test set up:
and getting the error: substr_count(): Empty substring in /var/www/html/functions.inc.php on line 5
Thanks for your help! Thanks
I don’t think you need a foreach loop if I get it right
echo keyword_count("this is text", "is");
PHP function substr_count()
There is already a built-in PHP function for counting substrings: substr_count(). If that is what you need, there is no need to implement your own function, it will probably be less performant and less error-prone.
This function, however, does not look exactly for words, but for substrings. Looking for «ban» on «We should ban bananas.» would return 2 instead of 1.
Your function substr_count_array()
If you still want to implement your own method. Let’s analyze your code:
- $count + 1 is returning the sum, but it is not changing the value of $count . To increment in PHP, you could use $count++ , $count += 1 or $count = $count + 1 .
- foreach ($word as $substring) is invalid. The first argument of foreach must be an array or an object. You cannot pass $word because it is a string.
- The $paragraph parameter is not being used. Without using it, your function substr_count_array() will not know the content of the paragraph and will never work properly.
PHP | count() Function, This inbuilt function of PHP is used to count the current elements in the array. The function might return 0 for the variable that has been
Php recursive array counting
I’m trying to write a function which counts array elements recursively.
$schema = array( 'div' => array( 'class' => 'lines', 'div' => array( 'span' => array( 'key' => 'Product Name' ), 'val' => 'Soap' ), 'layer' => array( 'span' => array( 'key' => 'Product Name' ), 'val' => 'Ball' ) ) ); function count_r($array, $i = 0) < foreach($array as $k)< if(is_array($k))< $i += count_r($k, count($k)); >else < $i++; >> return $i; > echo count_r($schema);
This is the second result on Google so I’m adding this as a reference. There is already a built-in function in PHP that you can use: count().
count($schema, COUNT_RECURSIVE);
This function can also detect recursion to avoid infinite loops so it’s safer than solutions in other answers.
PHP has a built-in method for this purpose, called count() . If passed without any additional parameters, count() returns the number of array keys on the first level. But, if you pass a second parameter to the count method count( $schema, true ) , then the result will be the total number of keys in the multi-dimensional array. The response marked as correct only iterates first and second level arrays, if you have a third child in that array, it will not return the correct answer.
This could be written as a recursive function, if you really want to write your own count() method, though.
If you want to count specific keys/values you can use the built-in array_walk_recursive with a closure function.
$schema = array( 'div' => array( 'class' => 'lines', 'div' => array( 'span' => array( 'key' => 'Product Name' ), 'val' => 'Soap' ), 'layer' => array( 'span' => array( 'key' => 'Product Name' ), 'val' => 'Ball' ) ) ); $elements = 0; array_walk_recursive($schema, function($value, $key) use (&$elements) < if (strstr($value, 'Product')) $elements++; >); print $elements; // 2 /* Values lines Product Name Soap Product Name Ball Keys class key val key val */
Transferred from comment below answer:
Basically, as you’re adding the count_r of that array to the current level, you don’t need to factor in the count in the second argument — you’d basically be adding it twice. You need the «1» in there, however, to count the array itself. If you’d want to count just the elements and not the arrays, you would just make the «1» a «0».
$schema = array( 'div' => array( 'class' => 'lines', 'div' => array( 'span' => array( 'key' => 'Product Name' ), 'val' => 'Soap' ), 'layer' => array( 'span' => array( 'key' => 'Product Name' ), 'val' => 'Ball' ) ) ); function count_r($array, $i = 0) < foreach($array as $k)< if(is_array($k))< $i += count_r($k, 1); >else < $i++; >> return $i; > echo count_r($schema);
This is tested and works correctly.
Python String count() Method, The count() method returns the number of times a specified value appears in the string. Syntax. string.count(value, start, end). Parameter Values. Parameter