I'm trying to write a function which counts array elements recursively.
But result is false.
What could it be problem?
$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);
You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.
//Number of elements present in an array can be calculated as follows. int length = sizeof(arr)/sizeof(arr[0]);
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 set to an empty array. Also for the variable which is not set the function returns 0.
The count() function returns the number of elements in an array.
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().
You can use it like this:
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With