PHP | DOMNamedNodeMap count() Function

The DOMNamedNodeMap::count() function is an inbuilt function in PHP which is used to get the number of nodes in the map. It can be used to count attributes of a element.

Syntax:

int DOMNamedNodeMap::count( void )

Parameters: This function doesn’t accepts any parameter.

Return Value: This function returns and integer value containing the number of nodes in the map.

Below examples illustrate the DOMNamedNodeMap::count() function in PHP:



Example 1: In this example we will count the attributes of a element.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
   
// Load the XML
$dom->loadXML("<?xml version=\"1.0\"?>
<root>
    <html>
        <h1 id=\"first\" 
            class=\"first\" 
            style=\"color: blue\"> 
         Geeksforgeeks 
        </h1>
    </html>
</root>");
   
// Get the elements
$node = $dom->getElementsByTagName('h1')[0];
   
// Get the attribute count
$attributeCount = $node->attributes->count();
echo 'No of attributes => ' . $attributeCount;
?>

chevron_right


Output:

No of attributes => 3

Example 2: In this example we will check if count function fetches the latest no of attributes or not by altering the number of attributes.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
   
// Load the XML
$dom->loadXML("<?xml version=\"1.0\"?>
<root>
    <html>
        <h1 id=\"first\"
            class=\"first\"> 
          Geeksforgeeks 
        </h1>
        <h2> Second heading </h2>
    </html>
</root>");
   
// Get the elements
$node = $dom->getElementsByTagName('h1')[0];
    
echo "Before the addition of attributes: <br>";
   
// Get the attribute count
$attributeCount = $node->attributes->count();
echo 'No of attributes => ' . $attributeCount;
    
// Set the id attribute
$node->setAttribute('new', 'value');
    
echo "<br>After the addition of attributes: <br>";
    
// Get the attribute count
$attributeCount = $node->attributes->count();
echo 'No of attributes => ' . $attributeCount;
?>

chevron_right


Output:

Before the addition of attributes:
No of attributes => 2
After the addition of attributes:
No of attributes => 3

Reference: https://www.php.net/manual/en/domnamednodemap.count.php




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.