Open In App

PHP iterator_apply() Function

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.

Return Values: The iterator_apply() function returns the iterator element.



Program 1: The following program demonstrates the iterator_apply() function.




<?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
  
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


Article Tags :