Skip to content

count()

Introduction

SimpleXML is a PHP extension that provides a simple and easy-to-use API for working with XML documents. The count() function is a built-in PHP function that works seamlessly with SimpleXML objects to count child elements or attributes. In this article, we will discuss how to use count() with SimpleXML in PHP.

Understanding the count() function with SimpleXML

The count() function in PHP returns the number of elements in an array or the number of properties/children of an object. When used with a SimpleXMLElement object, it counts the number of child elements. The syntax for using the count() function is as follows:

php
count(mixed $value, int $mode = COUNT_NORMAL): int

Here, $value is the SimpleXML object or array to count. The optional $mode parameter determines whether to count recursively (COUNT_RECURSIVE or 1). By default, it only counts immediate children. Note that count() counts child elements. To count attributes, use count($element->attributes()). Note that COUNT_RECURSIVE is primarily designed for nested arrays; with SimpleXML, it counts all descendant elements recursively rather than just immediate children.

Example Usage

Let's look at an example to understand the usage of count() with SimpleXML in PHP:

php
<?php

$xml = new SimpleXMLElement('<books><book><title>PHP Basics</title><author>John Doe</author></book></books>');
$count = count($xml->book);
echo $count; // Outputs: 1

In the example above, we first create a SimpleXMLElement object that represents an XML document containing a single <code><book></code> element. We then use the global count() function to count the number of <code><book></code> child elements of the root node. Finally, we print the count.

To count attributes on an element, you can pass the result of attributes() to count():

php
$attrs = count($xml->book->attributes());
echo $attrs; // Outputs: 0

Conclusion

The count() function is an essential tool for working with XML documents in PHP. By passing a SimpleXMLElement object to this built-in function, developers can quickly determine the number of child elements using a straightforward syntax. We hope this overview helps you integrate count() into your PHP projects effectively.

Practice

What does the count() function do in PHP?

Dual-run preview — compare with live Symfony routes.