PHP iterator_apply() Function
Last Updated :
09 Aug, 2023
The iterator_apply() function is an inbuilt function in PHP that is used to apply a user-defined callback function to each element of an iterator. It allows you to iterate any element without using any kind of loop.
Syntax:
int iterator_apply(
Traversable $iterator,
callable $callback,
?array $args = nul
l): int
Parameters: This function accepts three parameters that are described below.
- $iterator: The iterator on which the callback function will be applied
- $funtion: This is the callback function. That is to call every single element. It must be returned ‘true’ for further calling.
- $args: An array of arguments; each element of
args
is passed to the callback callback
as a separate argument.
Return Values: The iterator_apply() function returns the iterator element.
Program 1: The following program demonstrates the iterator_apply() function.
PHP
<?php
function check_for_a(Iterator $iterator ) {
$element = $iterator ->current();
if ( stripos ( $element , 'a' ) !== false) {
echo "Element '$element' " .
"contains the letter 'a'.\n" ;
} else {
echo "Element '$element' " .
"does not contain the letter 'a'.\n" ;
}
return TRUE;
}
$fruits = array (
"Orange" ,
"Banana" ,
"Grapes" ,
"Kiwi"
);
$arrIter = new ArrayIterator( $fruits );
iterator_apply( $arrIter ,
"check_for_a" , array ( $arrIter ));
?>
|
Output
Element 'Orange' contains the letter 'a'.
Element 'Banana' contains the letter 'a'.
Element 'Grapes' contains the letter 'a'.
Element 'Kiwi' does not contain the letter 'a'.
Program 2: The following program demonstrates the iterator_apply() function.
PHP
<?php
function print_positive_integers(Iterator $iterator ) {
$element = $iterator ->current();
if ( is_int ( $element ) && $element > 0) {
echo "Positive Integer: $element\n" ;
}
return TRUE;
}
$arr = array (10, -5, 20, -15, 30, 0, 25, -8, 40);
$arrIter = new ArrayIterator( $arr );
iterator_apply(
$arrIter ,
"print_positive_integers" ,
array ( $arrIter )
);
?>
|
Output
Positive Integer: 10
Positive Integer: 20
Positive Integer: 30
Positive Integer: 25
Positive Integer: 40
Reference: https://www.php.net/manual/en/function.iterator-apply.php
Share your thoughts in the comments
Please Login to comment...