PHP | ArrayObject setIteratorClass() Function

The ArrayObject::setIteratorClass() function is an inbuilt function in PHP which is used to set the iterator classname for the ArrayObject.

Syntax:

void ArrayObject::setIteratorClass( string $iterator_class )

Parameters: This function accepts single parameter $iterator_class which holds the class name of the array iterator. It is used when iterating it over this object.



Return Value: This function does not return any value.

Below programs illustrate the ArrayObject::setIteratorClass() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
// PHP program to illustrate the 
// ArrayObject::setIteratorClass() function 
  
// Custom ArrayIterator (inherits from ArrayIterator)
class iteratorClass extends ArrayIterator {
  
}
  
// Create array object 
$arrayObjectElement = new ArrayObject(
    array('Geeks', 'for', 'Geeks')
); 
  
// Use ArrayObject::setIteratorClass() function
// to set the iterator classname for the ArrayObject
$arrayObjectElement->setIteratorClass('iteratorClass');
  
print_r($arrayObjectElement->getIterator());
  
?>

chevron_right


Output:

iteratorClass Object
(
    [storage:ArrayIterator:private] => ArrayObject Object
        (
            [storage:ArrayObject:private] => Array
                (
                    [0] => Geeks
                    [1] => for
                    [2] => Geeks
                )

        )

)

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
// PHP program to illustrate the 
// ArrayObject::setIteratorClass() function 
  
// Custom ArrayIterator (inherits from ArrayIterator)
class iteratorClass extends ArrayIterator {
  
}
  
// Declare an associative array
$arr = array(
    "a" => "Welcome",
    "b" => "to"
    "d" => "GeeksforGeeks"
); 
  
// Create array object 
$arrayObjectElement = new ArrayObject($arr); 
  
// Use ArrayObject::setIteratorClass() function
// to set the iterator classname for the ArrayObject
$arrayObjectElement->setIteratorClass('iteratorClass');
  
print_r($arrayObjectElement->getIterator());
  
?>

chevron_right


Output:

iteratorClass Object
(
    [storage:ArrayIterator:private] => ArrayObject Object
        (
            [storage:ArrayObject:private] => Array
                (
                    [a] => Welcome
                    [b] => to
                    [d] => GeeksforGeeks
                )

        )

)

Reference: https://www.php.net/manual/en/arrayobject.setiteratorclass.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.