- How to Count Object Length in PHP using Count() Function
- Counting elements of an array with count()
- Counting properties of an object with count()
- Counting properties of a stdClass object
- Counting objects within another object
- Implementing the Countable interface in custom objects with SPL
- Other helpful PHP count() function code samples
- Conclusion
- Frequently Asked Questions — FAQs
- How does the count() function work in PHP?
- Can count() be used to count the number of elements in a multidimensional array?
- How do I count the number of properties in a custom object?
- Can count() be used to count the number of elements in an associative array?
- How do I count the number of objects within another object?
- Is it possible to count the number of properties in a stdClass object?
- count
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- count
- Parameters
- Return Values
- Changelog
- Examples
- See Also
How to Count Object Length in PHP using Count() Function
Learn how to count the length of an object in PHP using the count() function. This article covers counting array elements, object properties, stdClass objects, nested objects, and custom objects using SPL.
- Counting elements of an array with count()
- Counting properties of an object with count()
- Counting properties of a stdClass object
- Counting objects within another object
- Implementing the Countable interface in custom objects with SPL
- Other helpful PHP count() function code samples
- Conclusion
- How to count the length of an object in PHP?
- How to count array of objects in PHP?
- How does count () work in PHP?
- How to find the length of a list in PHP?
If you are working with PHP, you must have come across situations where you need to count the length of an object. PHP provides a built-in function called count() that can be used to count the elements of an array or the properties of an object. In this article, we will discuss how to use count() to count the length of an object in PHP.
Counting elements of an array with count()
The count() function can be used to count the elements of an array. When used with an array, it counts all elements in the array. Here is an example code:
$arr = array('apple', 'banana', 'orange'); $count = count($arr); // $count is 3.
Counting properties of an object with count()
When used with an object that implements the Countable interface, count() returns the return value of ArrayObject::count() . ArrayObject::count() is used to get the number of public properties in the ArrayObject . Here is an example code:
$obj = new ArrayObject(array('foo' => 'bar', 'baz' => 'qux')); $count = count($obj); // $count is 2.
Counting properties of a stdClass object
To count the number of properties in a stdClass object, you can cast it to an array and use the count() function on the resulting array. Here is an example code:
$obj = new stdClass(); $obj->foo = 'bar'; $obj->baz = 'qux'; $count = count((array)$obj); // $count is 2.
Counting objects within another object
To count the number of objects within another object, you can use the count() function on the object’s property that contains the objects. Here is an example code:
$obj = new stdClass(); $obj->foo = new stdClass(); $obj->foo->bar = new stdClass(); $count = count($obj->foo); // $count is 1.
Implementing the Countable interface in custom objects with SPL
SPL can be used to implement the Countable interface in custom objects. This allows the use of count() on these objects. Here is an example code:
class CustomObject implements Countable < public function count() < // count implementation here >>
Other helpful PHP count() function code samples
In Php , for instance, count object php code sample
In Php , in particular, how to get length of object in php code example
Conclusion
Counting the length of an object in PHP can be done using the count() function. This function can count the elements of an array or the properties of an object. By following the tips and tricks mentioned in this article, you can use count() to count the length of any object in PHP.
In conclusion, counting the length of an object in PHP using the count() function is simple and straightforward. This function can be used to count the elements of an array or the properties of an object. By implementing the Countable interface in custom objects with SPL, you can use count() on these objects as well. With the help of the examples provided in this article, you should be able to easily count the length of any object in PHP.
Frequently Asked Questions — FAQs
How does the count() function work in PHP?
The count() function in PHP is used to count the number of elements in an array or the number of properties in an object. It returns an integer value representing the count.
Can count() be used to count the number of elements in a multidimensional array?
Yes, count() can be used to count the number of elements in a multidimensional array. When used with a multidimensional array, it counts all elements in all dimensions.
How do I count the number of properties in a custom object?
To count the number of properties in a custom object, you can implement the Countable interface using SPL. This allows the use of count() on the custom object.
Can count() be used to count the number of elements in an associative array?
Yes, count() can be used to count the number of elements in an associative array. When used with an associative array, it counts all elements in the array.
How do I count the number of objects within another object?
To count the number of objects within another object, you can use the count() function on the object’s property that contains the objects.
Is it possible to count the number of properties in a stdClass object?
Yes, you can count the number of properties in a stdClass object by casting it to an array and using the count() function on the resulting array.
count
Подсчитывает количество элементов массива или что-то в объекте.
Для объектов, если у вас включена поддержка SPL, вы можете перехватить count() , реализуя интерфейс Countable. Этот интерфейс имеет ровно один метод, Countable::count() , который возвращает значение функции count() .
Пожалуйста, смотрите раздел «Массивы» в этом руководстве для более детального представления о реализации и использовании массивов в PHP.
Список параметров
Если необязательный параметр mode установлен в COUNT_RECURSIVE (или 1), count() будет рекурсивно подсчитывать количество элементов массива. Это особенно полезно для подсчёта всех элементов многомерных массивов.
count() умеет определять рекурсию для избежания бесконечного цикла, но при каждом обнаружении выводит ошибку уровня E_WARNING (в случае, если массив содержит себя более одного раза) и возвращает большее количество, чем могло бы ожидаться.
Возвращаемые значения
Возвращает количество элементов в array_or_countable . Если параметр не является массивом или объектом, реализующим интерфейс Countable, будет возвращена 1. За одним исключением: если array_or_countable — NULL , то будет возвращён 0.
count() может возвратить 0 для переменных, которые не установлены, но также может возвратить 0 для переменных, которые инициализированы пустым массивом. Используйте функцию isset() для того, чтобы протестировать, установлена ли переменная.
Примеры
Пример #1 Пример использования count()
$a [ 0 ] = 1 ;
$a [ 1 ] = 3 ;
$a [ 2 ] = 5 ;
$result = count ( $a );
// $result == 3
?php
$b [ 0 ] = 7 ;
$b [ 5 ] = 9 ;
$b [ 10 ] = 11 ;
$result = count ( $b );
// $result == 3
$result = count ( null );
// $result == 0
$result = count ( false );
// $result == 1
?>
Пример #2 Пример рекурсивного использования count()
$food = array( ‘fruits’ => array( ‘orange’ , ‘banana’ , ‘apple’ ),
‘veggie’ => array( ‘carrot’ , ‘collard’ , ‘pea’ ));
?php
// рекурсивный count
echo count ( $food , COUNT_RECURSIVE ); // выводит 8
// обычный count
echo count ( $food ); // выводит 2
Смотрите также
- is_array() — Определяет, является ли переменная массивом
- isset() — Определяет, была ли установлена переменная значением отличным от NULL
- strlen() — Возвращает длину строки
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