Current Location: Home> Function Categories> iterator_apply

iterator_apply

Call a user-defined function for each element in the iterator
Name:iterator_apply
Category:SPL
Programming Language:php
One-line Description:Apply a function to each element in the iterator

Function name: iterator_apply()

Applicable version: PHP 5, PHP 7

Function Description: the iterator_apply() function applies a function to each element in the iterator.

Syntax: iterator_apply(Iterator $iterator, callable $function [, array $args = NULL])

parameter:

  • $iterator: Required, iterator object to apply the function.
  • $function: Required, function or method to apply. It can be an anonymous function, a normal function or a class method.
  • $args: Optional, a list of parameters passed to the function, provided as an array.

Return value: Returns the result of the function call when successful, and returns FALSE when failure.

Example:

 // 创建一个数组迭代器$array = new ArrayIterator(['apple', 'banana', 'cherry']); // 定义一个函数,将每个元素转换为大写function toUpperCase($item) { return strtoupper($item); } // 应用函数到迭代器中的每个元素iterator_apply($array, 'toUpperCase'); // 输出转换后的结果foreach ($array as $item) { echo $item . ' '; // 输出:APPLE BANANA CHERRY }

Notes:

  • The iterator object must implement the Iterator interface.
  • A function or method must accept a parameter that represents each element in the iterator.
  • If a function or method requires multiple parameters, you can use the $args parameter to pass the parameter list. For example: iterator_apply($iterator, 'myFunction', [$arg1, $arg2, $arg3]) .
Similar Functions
Popular Articles