Home > Article > Backend Development > PHP counts the number of cells or object attributes in an array
php editor Strawberry introduces you how to calculate the number of units or object attributes in a PHP array. In PHP, you can use the count() function to get the number of units in an array, or you can use the count() or sizeof() function to get the number of attributes of an object. These functions can help you quickly and accurately count the number of elements in an array or object, making programming more efficient and easier. Next, let’s learn in detail how to implement these functions in PHP.
Calculate the number of cells or object attributes in the array
Array
<?php $array = array(1, 2, 3, array(4, 5, 6)); echo count($array); // Output: 4 ?>
<?php $array = array(1, 2, 3, array(4, 5, 6)); echo sizeof($array); // Output: 4 ?>
Object
The number of object attributes can be calculated by the following method:
<?php class Person { public $name; public $age; } $person = new Person(); $person->name = "John Doe"; $person->age = 30; echo count($person); // Output: 2 ?>
<?php class Person { public $name; public $age; } $person = new Person(); $person->name = "John Doe"; $person->age = 30; $properties = get_object_vars($person); echo count($properties); // Output: 2 ?>
<?php class Person { public $name; public $age; } $person = new Person(); $person->name = "John Doe"; $person->age = 30; $propertyNames = array_keys(get_object_vars($person)); echo count($propertyNames); // Output: 2 ?>
Nested Arrays and Objects
If an array or object contains other arrays or objects, you can use the recursive method to calculate the total number of its cells or properties.
<?php function countNestedArray($array) { $count = 0; foreach ($array as $value) { if (is_array($value)) { $count = countNestedArray($value); } else { $count ; } } return $count; } ?>
<?php class Person { public $name; public $age; public $children; } function countNestedObject($object) { $count = 0; foreach ($object as $property => $value) { if (is_object($value)) { $count = countNestedObject($value); } else { $count ; } } return $count; } ?>
The above is the detailed content of PHP counts the number of cells or object attributes in an array. For more information, please follow other related articles on the PHP Chinese website!