/** * Map an array or traversable to another array. * * @param callable $mapper a mapper to map each value; * value will be passed to the mapper as the first argument, * key will be passed as the second one * @param array|\Traversable $traversable the traversable to map * @param bool $with_keys pass key to the mapper as second argument * (optional, default is false) * @return array the mapped array */ function traversable_map(callable $mapper, $traversable, bool $with_keys = false) : array { $array_mapped = []; foreach (to_traversable($traversable) as $key => $value) { $array_mapped[$key] = $with_keys ? call_user_func($mapper, $value, $key) : call_user_func($mapper, $value); } return $array_mapped; }
/** * Iteratively reduce an array or a traversable to a single value * using a callback function. * * Function applies iteratively the callback function to elements and keys * of the array or the traversable, so as to reduce it to a single value. * * @param callable $callback the callback to apply to each element and key; * current intermediate result will be passed as the first argument * (in the case of the first iteration it instead holds the value of * <code>$initial</code>), current value will be passed as the second one, * current key will be passed as the third one; callback must return * new intermediate result * @param mixed $initial initial value * @param array|\Traversable $traversable the input traversable * @return mixed the resulting value */ function traversable_reduce(callable $callback, $initial, $traversable) { $result = $initial; foreach (to_traversable($traversable) as $key => $value) { $result = call_user_func($callback, $result, $value, $key); } return $result; }
/** * Filter an array or a traversable. * * @param callable $predicate a predicate to test each value and key; * value will be passed to the predicate as the first argument, * key will be passed as the second one * @param array|\Traversable $traversable the traversable to filter * @param bool $with_keys pass key to the predicate as second argument * (optional, default is false) * @return array the filtered array */ function traversable_filter(callable $predicate, $traversable, bool $with_keys = false) : array { $array_filtered = []; foreach (to_traversable($traversable) as $key => $value) { $result = $with_keys ? call_user_func($predicate, $value, $key) : call_user_func($predicate, $value); if (!$result) { continue; } $array_filtered[$key] = $value; } return $array_filtered; }
/** * Walk on an array or traversable. * * @param callable $action an action to perform with each item and key of the traversable; * value will be passed to the action as the first argument, * key will be passed as the second one * @param array|\Traversable $traversable the traversable to walk on */ function traversable_walk(callable $action, $traversable) { foreach (to_traversable($traversable) as $key => $value) { call_user_func($action, $value, $key); } }