beans_count_recursive

Count recursive array.

This function is able to count a recursive array. The depth can be defined as well as if the parent should be counted. For instance, if $depth is defined and $count_parent is set to false, only the level of the defined depth will be counted.

beans_count_recursive( string $array, int|bool $depth = false, bool $count_parent = true )

Return: (int) Number of entries found.

Parameters

NameTypeRequiredDefaultDescription
$arraystringtrue-The array.
$depthint|boolfalsefalseDepth until which the entries should be counted.
$count_parentboolfalsetrueWhether the parent should be counted or not.

Source

function beans_count_recursive( $array, $depth = false, $count_parent = true ) {

	if ( ! is_array( $array ) ) {
		return 0;
	}

	if ( 1 === $depth ) {
		return count( $array );
	}

	if ( ! is_numeric( $depth ) ) {
		return count( $array, COUNT_RECURSIVE );
	}

	$count = $count_parent ? count( $array ) : 0;

	foreach ( $array as $_array ) {

		if ( is_array( $_array ) ) {
			$count += beans_count_recursive( $_array, $depth - 1, $count_parent );
		} else {
			$count += 1;
		}
	}

	return $count;

}