PHP.nl

count

count

Counts all elements in an array or in a Countable object

int **count**  $value int $mode

Counts all elements in an array when used with an array. When used with an object that implements the interface, it returns the return value of the method . Countable``Countable::count

value An array or object. Countable

mode If the optional parameter is set to (or 1), will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. mode``COUNT_RECURSIVE``count

Let op: > can detect recursion to avoid an infinite loop, but will emit an every time it does (in case the array contains itself more than once) and return a count higher than may be expected. count``E_WARNING

Returns the number of elements in . Prior to PHP 8.0.0, if the parameter was neither an array nor an object that implements the interface, would be returned, unless was null, in which case would be returned. value``Countable``1``value``0

Voorbeeld: example

<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
var_dump(count($a));

$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
var_dump(count($b));
?>
int(3)
int(3)

Voorbeeld: non Countable|array example (bad example - don't do this)

<?php
$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
var_dump(count($b));

var_dump(count(null));

var_dump(count(false));
?>
int(3)

Fatal error: Uncaught TypeError: count(): Argument #1 ($var) must be of type Countable .. on line 12

Voorbeeld: Recursive example

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

// recursive count
var_dump(count($food, COUNT_RECURSIVE));

// normal count
var_dump(count($food));

?>
int(8)
int(2)

Voorbeeld: object

<?php
class CountOfMethods implements Countable
{
    private function someMethod()
    {
    }

    public function count(): int
    {
        return count(get_class_methods($this));
    }
}

$obj = new CountOfMethods();
var_dump(count($obj));
?>
int(2)

is_array``isset``empty``strlen``is_countableArrays