README.md

May 3, 2026 · View on GitHub

IterToolsLogo Logo

IterTools - PHP Iteration Tools to Power Up Your Loops

Inspired by Python—designed for PHP.

Coverage Status License Latest Stable Version Downloads

Features

IterTools makes you an iteration superstar by providing two types of tools:

  • Loop iteration tools
  • Stream iteration tools

Loop Iteration Tools Example

foreach (Multi::zip(['a', 'b'], [1, 2]) as [$letter, $number]) {
    print($letter . $number);  // a1, b2
}

Stream Iteration Tools Example

$result = Stream::of([1, 1, 2, 2, 3, 4, 5])
    ->distinct()                 // [1, 2, 3, 4, 5]
    ->map(fn ($x) => $x**2)      // [1, 4, 9, 16, 25]
    ->filter(fn ($x) => $x < 10) // [1, 4, 9]
    ->toSum();                   // 14

All functions work on iterable collections:

  • array (type)
  • Generator (type)
  • Iterator (interface)
  • Traversable (interface)

README docs translated in other languages:

Setup

Add the library to your composer.json file in your project:

{
  "require": {
      "markrogoyski/itertools-php": "2.*"
  }
}

Use composer to install the library:

$ composer install

Composer will install IterTools inside your vendor folder. Then you can add the following to your .php files to use the library with Autoloading.

require_once __DIR__ . '/vendor/autoload.php';

Alternatively, use composer on the command line to require and install IterTools:

$ composer require markrogoyski/itertools-php:2.*

Minimum Requirements

  • PHP 8.2+
    • (For PHP 7.4–8.1, use v1.9)

Quick Reference

Loop Iteration Tools

Multi Iteration

IteratorDescriptionCode Snippet
chainChain multiple iterables togetherMulti::chain($list1, $list2)
roundRobinYield one value at a time from multiple iterables, rotating across sourcesMulti::roundRobin($list1, $list2)
zipIterate multiple collections simultaneously until the shortest iterator completesMulti::zip($list1, $list2)
zipEqualIterate multiple collections of equal length simultaneously, error if lengths not equalMulti::zipEqual($list1, $list2)
zipFilledIterate multiple collections, using a filler value if lengths not equalMulti::zipFilled($default, $list1, $list2)
zipLongestIterate multiple collections simultaneously until the longest iterator completesMulti::zipLongest($list1, $list2)
unzipTranspose a sequence of rows into columns (inverse of zip)Multi::unzip($rows)

Single Iteration

IteratorDescriptionCode Snippet
accumulateRunning result of a binary operatorSingle::accumulate($data, $op, [$initial])
chunkwiseIterate by chunksSingle::chunkwise($data, $chunkSize)
chunkwiseOverlapIterate by overlapped chunksSingle::chunkwiseOverlap($data, $chunkSize, $overlapSize)
compressFilter out elements not selectedSingle::compress($data, $selectors)
compressAssociativeFilter out elements by keys not selectedSingle::compressAssociative($data, $selectorKeys)
dropWhileDrop elements while predicate is trueSingle::dropWhile($data, $predicate)
enumerateIterate [index, value] pairsSingle::enumerate($data, [$start])
filterFilter for elements where predicate is trueSingle::filterTrue($data, $predicate)
filterTrueFilter for truthy elementsSingle::filterTrue($data)
filterFalseFilter for falsy elementsSingle::filterFalse($data)
filterKeysFilter for keys where predicate is trueSingle::filterKeys($data, $predicate)
flatMapMap function onto items and flatten resultSingle::flaMap($data, $mapper)
flattenFlatten multidimensional iterableSingle::flatten($data, [$dimensions])
groupAdjacentByGroup adjacent elements sharing an extracted keySingle::groupAdjacentBy($data, $keyFn)
groupByGroup data by a common elementSingle::groupBy($data, $groupKeyFunction, [$itemKeyFunc])
intersperseInsert a separator between elementsSingle::intersperse($data, $separator)
limitIterate up to a limitSingle::limit($data, $limit)
mapMap function onto each itemSingle::map($data, $function)
mapSpreadMap function onto each item, splatting items as positional argsSingle::mapSpread($data, $function)
padLeftPad iterable on the left to a minimum lengthSingle::padLeft($data, $length, $fill)
padRightPad iterable on the right to a minimum lengthSingle::padRight($data, $length, $fill)
pairwiseIterate successive overlapping pairsSingle::pairwise($data)
reindexReindex keys of key-value iterableSingle::reindex($data, $reindexer)
repeatRepeat an item a number of timesSingle::repeat($item, $repetitions)
reverseIterate elements in reverse orderSingle::reverse($data)
skipIterate after skipping elementsSingle::skip($data, $count, [$offset])
sliceExtract a slice of the iterableSingle::slice($data, [$start], [$count], [$step])
splitWhenSplit iterable into groups when predicate matchesSingle::splitWhen($data, $predicate)
stringIterate the characters of a stringSingle::string($string)
takeWhileIterate elements while predicate is trueSingle::takeWhile($data, $predicate)

Infinite Iteration

IteratorDescriptionCode Snippet
countCount sequentially foreverInfinite::count($start, $step)
cycleCycle through a collectionInfinite::cycle($collection)
generateYield values from a supplier foreverInfinite::generate($supplier)
iterateIterate by repeatedly applying a functionInfinite::iterate($initial, $function)
repeatRepeat an item foreverInfinite::repeat($item)

Random Iteration

IteratorDescriptionCode Snippet
choiceRandom selections from listRandom::choice($list, $repetitions)
coinFlipRandom coin flips (0 or 1)Random::coinFlip($repetitions)
numberRandom numbersRandom::number($min, $max, $repetitions)
percentageRandom percentage between 0 and 1Random::percentage($repetitions)
rockPaperScissorsRandom rock-paper-scissors handsRandom::rockPaperScissors($repetitions)
sampleRandom sample without replacementRandom::sample($data, $size, [$engine])

Math Iteration

IteratorDescriptionCode Snippet
frequenciesFrequency distribution of dataMath::frequencies($data, [$strict])
relativeFrequenciesRelative frequency distribution of dataMath::relativeFrequencies($data, [$strict])
runningAverageRunning average accumulationMath::runningAverage($numbers, $initialValue)
runningDifferenceRunning difference accumulationMath::runningDifference($numbers, $initialValue)
runningMaxRunning maximum accumulationMath::runningMax($numbers, $initialValue)
runningMinRunning minimum accumulationMath::runningMin($numbers, $initialValue)
runningProductRunning product accumulationMath::runningProduct($numbers, $initialValue)
runningTotalRunning total accumulationMath::runningTotal($numbers, $initialValue)

Set and multiset Iteration

IteratorDescriptionCode Snippet
distinctIterate only distinct itemsSet::distinct($data)
distinctAdjacentRemove only consecutive duplicatesSet::distinctAdjacent($data)
distinctAdjacentByRemove only consecutive duplicates using custom keySet::distinctAdjacentBy($data, $keyFn)
distinctByIterate only distinct items using custom comparatorSet::distinct($data, $compareBy)
duplicatesIterate values that appear more than onceSet::duplicates($data, [$strict])
duplicatesByIterate duplicates using a custom key functionSet::duplicatesBy($data, $keyFn)
intersectionIntersection of iterablesSet::intersection(...$iterables)
intersectionCoerciveIntersection with type coercionSet::intersectionCoercive(...$iterables)
partialIntersectionPartial intersection of iterablesSet::partialIntersection($minCount, ...$iterables)
partialIntersectionCoercivePartial intersection with type coercionSet::partialIntersectionCoercive($minCount, ...$iterables)
differenceDifference of iterablesSet::difference($a, ...$iterables)
differenceCoerciveDifference with type coercionSet::differenceCoercive($a, ...$iterables)
symmetricDifferenceSymmetric difference of iterablesSet::symmetricDifference(...$iterables)
symmetricDifferenceCoerciveSymmetric difference with type coercionSet::symmetricDifferenceCoercive(...$iterables)
unionUnion of iterablesSet::union(...$iterables)
unionCoerciveUnion with type coercionSet::unionCoercive(...$iterables)

Combinatorics

IteratorDescriptionCode Snippet
productCartesian product of iterablesCombinatorics::product(...$iterables)
permutationsPermutations of an iterableCombinatorics::permutations($data, [$r])
combinationsCombinations of an iterableCombinatorics::combinations($data, $r)
combinationsWithReplacementCombinations with replacementCombinatorics::combinationsWithReplacement($data, $r)
powersetEvery subset of an iterableCombinatorics::powerset($data)

Sort Iteration

IteratorDescriptionCode Snippet
asortIterate a sorted collection maintaining keysSort::asort($data, [$comparator])
asortByIterate sorted by extracted key, keys keptSort::asortBy($data, $keyFn)
largestIterate the n largest elements (descending)Sort::largest($data, $n, [$keyFn])
shuffleIterate the iterable in random orderSort::shuffle($data, [$engine])
smallestIterate the n smallest elements (ascending)Sort::smallest($data, $n, [$keyFn])
sortIterate a sorted collectionSort::sort($data, [$comparator])
sortByIterate sorted by extracted keySort::sortBy($data, $keyFn)

File Iteration

IteratorDescriptionCode Snippet
readCsvIntersection a CSV file line by lineFile::readCsv($fileHandle)
readLinesIterate a file line by lineFile::readLines($fileHandle)

Transform Iteration

IteratorDescriptionCode Snippet
partitionPartition iterable into truthy and falsy listsTransform::partition($data, $predicate)
teeIterate duplicate iteratorsTransform::tee($data, $count)
toArrayTransform iterable to an arrayTransform::toArray($data)
toAssociativeArrayTransform iterable to an associative arrayTransform::toAssociativeArray($data, [$keyFunc], [$valueFunc])
toIteratorTransform iterable to an iteratorTransform::toIterator($data)

Summary

SummaryDescriptionCode Snippet
allMatchTrue if all items are true according to predicateSummary::allMatch($data, $predicate)
allUniqueTrue if all items are uniqueSummary::allUnique($data, [$strict])
anyMatchTrue if any item is true according to predicateSummary::anyMatch($data, $predicate)
arePermutationsTrue if iterables are permutations of each otherSummary::arePermutations(...$iterables)
arePermutationsCoerciveTrue if iterables are permutations of each other with type coercionSummary::arePermutationsCoercive(...$iterables)
atLeastNTrue if at least n items are true according to predicateSummary::atLeastN($data, $n, [$predicate])
atMostNTrue if at most n items are true according to predicateSummary::atMostN($data, $n, [$predicate])
containsTrue if iterable contains the needleSummary::contains($data, $needle)
containsCoerciveTrue if iterable contains the needle with type coercionSummary::containsCoercive($data, $needle)
endsWithTrue if iterable ends with the given suffixSummary::endsWith($data, $suffix)
endsWithCoerciveTrue if iterable ends with the given suffix with type coercionSummary::endsWithCoercive($data, $suffix)
exactlyNTrue if exactly n items are true according to predicateSummary::exactlyN($data, $n, $predicate)
isEmptyTrue if iterable has no itemsSummary::isEmpty($data)
isPartitionedTrue if partitioned with items true according to predicate before othersSummary::isPartitioned($data, $predicate)
isSortedTrue if iterable sortedSummary::isSorted($data)
isReversedTrue if iterable reverse sortedSummary::isReversed($data)
noneMatchTrue if none of items true according to predicateSummary::noneMatch($data, $predicate)
sameTrue if iterables are the sameSummary::same(...$iterables)
sameCountTrue if iterables have the same lengthsSummary::sameCount(...$iterables)
startsWithTrue if iterable starts with the given prefixSummary::startsWith($data, $prefix)
startsWithCoerciveTrue if iterable starts with the given prefix with type coercionSummary::startsWithCoercive($data, $prefix)

Reduce

ReducerDescriptionCode Snippet
toAverageMean average of elementsReduce::toAverage($numbers)
toCountReduce to length of iterableReduce::toCount($data)
toFirstReduce to its first valueReduce::toFirst($data)
toFirstAndLastReduce to its first and last valuesReduce::toFirstAndLast($data)
toFirstMatchReduce to first value matching predicateReduce::toFirstMatch($data, $predicate, [$default])
toFirstMatchIndexReduce to position of first matching elementReduce::toFirstMatchIndex($data, $predicate, [$default])
toFirstMatchKeyReduce to key of first matching elementReduce::toFirstMatchKey($data, $predicate, [$default])
toLastReduce to its last valueReduce::toLast()
toLastMatchReduce to last value matching predicateReduce::toLastMatch($data, $predicate, [$default])
toLastMatchIndexReduce to position of last matching elementReduce::toLastMatchIndex($data, $predicate, [$default])
toLastMatchKeyReduce to key of last matching elementReduce::toLastMatchKey($data, $predicate, [$default])
toOnlyReduce to its sole elementReduce::toOnly($data)
consumeDrain iterable, discarding valuesReduce::consume($data)
toMaxReduce to its largest elementReduce::toMax($numbers, [$compareBy])
toMinReduce to its smallest elementReduce::toMin($numbers, [$compareBy])
toMinMaxReduce to array of upper and lower boundsReduce::toMinMax($numbers, [$compareBy])
toNthReduce to value at nth positionReduce::toNth($data, $position)
toProductReduce to the product of its elementsReduce::toProduct($numbers)
toRandomValueReduce to random value from iterableReduce::toRandomValue($data)
toRangeReduce to difference of max and min valuesReduce::toRange($numbers)
toStringReduce to joined stringReduce::toString($data, [$separator], [$prefix], [$suffix])
toSumReduce to the sum of its elementsReduce::toSum($numbers)
toValueReduce to value using callable reducerReduce::toValue($data, $reducer, $initialValue)

Stream Iteration Tools

Stream Sources

SourceDescriptionCode Snippet
ofCreate a stream from an iterableStream::of($iterable)
ofCoinFlipsCreate a stream of random coin flipsStream::ofCoinFlips($repetitions)
ofCsvFileCreate a stream from a CSV fileStream::ofCsvFile($fileHandle)
ofEmptyCreate an empty streamStream::ofEmpty()
ofFileLinesCreate a stream from lines of a fileStream::ofFileLines($fileHandle)
ofRandomChoiceCreate a stream of random selectionsStream::ofRandomChoice($items, $repetitions)
ofRandomNumbersCreate a stream of random numbers (integers)Stream::ofRandomNumbers($min, $max, $repetitions)
ofRandomPercentageCreate a stream of random percentages between 0 and 1Stream::ofRandomPercentage($repetitions)
ofRangeCreate a stream of a range of numbersStream::ofRange($start, $end, $step)
ofRockPaperScissorsCreate a stream of rock-paper-scissors handsStream::ofRockPaperScissors($repetitions)

Stream Operations

OperationDescriptionCode Snippet
accumulateRunning result of a binary operator$stream->accumulate($op, [$initial])
appendAppend values to the end of the stream$stream->append(...$values)
asortSorts the iterable source maintaining keys$stream->asort([$comparator])
asortBySorts the stream by extracted key, maintaining keys$stream->asortBy($keyFn)
chainWithChain iterable source withs given iterables together into a single iteration$stream->chainWith(...$iterables)
compressCompress source by filtering out data not selected$stream->compress($selectors)
compressAssociativeCompress source by filtering out keys not selected$stream->compressAssociative($selectorKeys)
chunkwiseIterate by chunks$stream->chunkwise($chunkSize)
chunkwiseOverlapIterate by overlapped chunks$stream->chunkwiseOverlap($chunkSize, $overlap)
distinctFilter out elements: iterate only unique items$stream->distinct([$strict])
distinctAdjacentRemove only consecutive duplicates$stream->distinctAdjacent()
distinctAdjacentByRemove only consecutive duplicates using custom key$stream->distinctAdjacentBy($keyFn)
distinctByFilter out elements: iterate only unique items using custom comparator$stream->distinct($compareBy)
dropWhileDrop elements from the iterable source while the predicate function is true$stream->dropWhile($predicate)
duplicatesIterate values that appear more than once$stream->duplicates([$strict])
duplicatesByIterate duplicates using a custom key function$stream->duplicatesBy($keyFn)
enumerateIterate [index, value] pairs$stream->enumerate([$start])
filterFilter for only elements where the predicate function is true$stream->filterTrue($predicate)
filterTrueFilter for only truthy elements$stream->filterTrue()
filterFalseFilter for only falsy elements$stream->filterFalse()
filterKeysFilter for keys where predicate function is true$stream->filterKeys($predicate)
flatMapMap function onto elements and flatten result$stream->flatMap($function)
flattenFlatten multidimensional stream$stream->flatten($dimensions)
frequenciesFrequency distribution$stream->frequencies([$strict])
groupAdjacentByGroup adjacent elements sharing an extracted key$stream->groupAdjacentBy($keyFn)
groupByGroup iterable source by a common data element$stream->groupBy($groupKeyFunction, [$itemKeyFunc])
infiniteCycleCycle through the elements of iterable source sequentially forever$stream->infiniteCycle()
intersectionWithIntersect iterable source and given iterables$stream->intersectionWith(...$iterables)
intersectionCoerciveWithIntersect iterable source and given iterables with type coercion$stream->intersectionCoerciveWith(...$iterables)
intersperseInsert a separator between elements of the stream$stream->intersperse($separator)
largestReduce the stream to the n largest elements (descending)$stream->largest($n, [$keyFn])
limitLimit the stream's iteration$stream->limit($limit)
mapMap function onto elements$stream->map($function)
mapSpreadMap function onto elements, splatting items as positional args$stream->mapSpread($function)
padLeftPad the stream on the left to a minimum length$stream->padLeft($length, $fill)
padRightPad the stream on the right to a minimum length$stream->padRight($length, $fill)
pairwiseReturn pairs of elements from iterable source$stream->pairwise()
partialIntersectionWithPartially intersect iterable source and given iterables$stream->partialIntersectionWith( $minIntersectionCount, ...$iterables)
partialIntersectionCoerciveWithPartially intersect iterable source and given iterables with type coercion$stream->partialIntersectionCoerciveWith( $minIntersectionCount, ...$iterables)
productWithCartesian product of stream with given iterables$stream->productWith(...$iterables)
permutationsPermutations of the stream's elements$stream->permutations([$r])
combinationsCombinations of the stream's elements$stream->combinations($r)
combinationsWithReplacementCombinations with replacement of the stream's elements$stream->combinationsWithReplacement($r)
powersetEvery subset of the stream's elements$stream->powerset()
prependPrepend values to the front of the stream$stream->prepend(...$values)
reindexReindex keys of key-value stream$stream->reindex($reindexer)
relativeFrequenciesRelative frequency distribution$stream->relativeFrequencies([$strict])
reverseReverse elements of the stream$stream->reverse()
roundRobinWithYield values from the stream and given iterables in round-robin order$stream->roundRobinWith(...$iterables)
runningAverageAccumulate the running average (mean) over iterable source$stream->runningAverage($initialValue)
runningDifferenceAccumulate the running difference over iterable source$stream->runningDifference($initialValue)
runningMaxAccumulate the running max over iterable source$stream->runningMax($initialValue)
runningMinAccumulate the running min over iterable source$stream->runningMin($initialValue)
runningProductAccumulate the running product over iterable source$stream->runningProduct($initialValue)
runningTotalAccumulate the running total over iterable source$stream->runningTotal($initialValue)
sampleSample $size elements from the stream without replacement$stream->sample($size, [$engine])
shuffleRandomize the order of the stream$stream->shuffle([$engine])
skipSkip some elements of the stream$stream->skip($count, [$offset])
sliceExtract a slice of the stream$stream->slice([$start], [$count], [$step])
smallestReduce the stream to the n smallest elements (ascending)$stream->smallest($n, [$keyFn])
sortSorts the stream$stream->sort([$comparator])
sortBySorts the stream by extracted key$stream->sortBy($keyFn)
splitWhenSplit the stream into groups when predicate matches$stream->splitWhen($predicate)
differenceWithDifference of iterable source and given iterables$stream->differenceWith(...$iterables)
differenceCoerciveWithDifference of iterable source and given iterables with type coercion$stream->differenceCoerciveWith(...$iterables)
symmetricDifferenceWithSymmetric difference of iterable source and given iterables$stream->symmetricDifferenceWith(...$iterables)
symmetricDifferenceCoerciveWithSymmetric difference of iterable source and given iterables with type coercion$stream->symmetricDifferenceCoerciveWith(...$iterables)
takeWhileReturn elements from the iterable source as long as the predicate is true$stream->takeWhile($predicate)
unionWithUnion of stream with iterables$stream->unionWith(...$iterables)
unionCoerciveWithUnion of stream with iterables with type coercion$stream->unionCoerciveWith(...$iterables)
unzipTranspose rows of the stream into columns (inverse of zip)$stream->unzip()
zipZip rows of the stream column-wise (transpose), stopping at shortest$stream->zip()
zipLongestZip rows of the stream column-wise, continuing until longest (missing → null)$stream->zipLongest()
zipFilledZip rows of the stream column-wise, continuing until longest with filler$stream->zipFilled($filler)
zipEqualZip rows of the stream column-wise, throwing if lengths differ$stream->zipEqual()
zipWithIterate iterable source with another iterable collection simultaneously$stream->zipWith(...$iterables)
zipEqualWithIterate iterable source with another iterable collection of equal lengths simultaneously$stream->zipEqualWith(...$iterables)
zipFilledWithIterate iterable source with another iterable collection using default filler$stream->zipFilledWith($default, ...$iterables)
zipLongestWithIterate iterable source with another iterable collection simultaneously$stream->zipLongestWith(...$iterables)

Stream Terminal Operations

Summary Terminal Operations
Terminal OperationDescriptionCode Snippet
allMatchReturns true if all items in stream match predicate$stream->allMatch($predicate)
allUniqueReturns true if all items in stream are unique$stream->allUnique([$strict]])
anyMatchReturns true if any item in stream matches predicate$stream->anyMatch($predicate)
arePermutationsWithReturns true if all iterables permutations of stream$stream->arePermutationsWith(...$iterables)
arePermutationsCoerciveWithReturns true if all iterables permutations of stream with type coercion$stream->arePermutationsCoerciveWith(...$iterables)
atLeastNReturns true if at least n items are true according to predicate$stream->atLeastN($n, [$predicate])
atMostNReturns true if at most n items are true according to predicate$stream->atMostN($n, [$predicate])
containsReturns true if stream contains the needle$stream->contains($needle)
containsCoerciveReturns true if stream contains the needle with type coercion$stream->containsCoercive($needle)
endsWithReturns true if stream ends with the given suffix$stream->endsWith($suffix)
endsWithCoerciveReturns true if stream ends with the given suffix with type coercion$stream->endsWithCoercive($suffix)
exactlyNReturns true if exactly n items are true according to predicate$stream->exactlyN($n, $predicate)
isEmptyReturns true if stream has no items$stream::isEmpty()
isPartitionedReturns true if partitioned with items true according to predicate before others$stream::isPartitioned($predicate)
isSortedReturns true if stream is sorted in ascending order$stream->isSorted()
isReversedReturns true if stream is sorted in reverse descending order$stream->isReversed()
noneMatchReturns true if none of the items in stream match predicate$stream->noneMatch($predicate)
sameWithReturns true if stream and all given collections are the same$stream->sameWith(...$iterables)
sameCountWithReturns true if stream and all given collections have the same lengths$stream->sameCountWith(...$iterables)
startsWithReturns true if stream starts with the given prefix$stream->startsWith($prefix)
startsWithCoerciveReturns true if stream starts with the given prefix with type coercion$stream->startsWithCoercive($prefix)
Reduction Terminal Operations
Terminal OperationDescriptionCode Snippet
toAverageReduces stream to the mean average of its items$stream->toAverage()
toCountReduces stream to its length$stream->toCount()
toFirstReduces stream to its first value$stream->toFirst()
toFirstAndLastReduces stream to its first and last values$stream->toFirstAndLast()
toFirstMatchReduces stream to first value matching predicate$stream->toFirstMatch($predicate, [$default])
toFirstMatchIndexReduces stream to position of first matching element$stream->toFirstMatchIndex($predicate, [$default])
toFirstMatchKeyReduces stream to key of first matching element$stream->toFirstMatchKey($predicate, [$default])
toLastReduces stream to its last value$stream->toLast()
toLastMatchReduces stream to last value matching predicate$stream->toLastMatch($predicate, [$default])
toLastMatchIndexReduces stream to position of last matching element$stream->toLastMatchIndex($predicate, [$default])
toLastMatchKeyReduces stream to key of last matching element$stream->toLastMatchKey($predicate, [$default])
toOnlyReduces stream to its sole element$stream->toOnly()
toMaxReduces stream to its max value$stream->toMax([$compareBy])
toMinReduces stream to its min value$stream->toMin([$compareBy])
toMinMaxReduces stream to array of upper and lower bounds$stream->toMinMax([$compareBy])
toNthReduces stream to value at nth position$stream->toNth($position)
toProductReduces stream to the product of its items$stream->toProduct()
toStringReduces stream to joined string$stream->toString([$separator], [$prefix], [$suffix])
toSumReduces stream to the sum of its items$stream->toSum()
toRandomValueReduces stream to random value within it$stream->toRandomValue()
toRangeReduces stream to difference of max and min values$stream->toRange()
toValueReduces stream like array_reduce() function$stream->toValue($reducer, $initialValue)
Transformation Terminal Operations
Terminal OperationDescriptionCode Snippet
toArrayReturns array of stream elements$stream->toArray()
toAssociativeArrayReturns key-value map of stream elements$stream->toAssociativeArray($keyFunc, $valueFunc)
toPartitionPartition stream into truthy and falsy lists$stream->toPartition($predicate)
teeReturns array of multiple identical Streams$stream->tee($count)
Side Effect Terminal Operations
Terminal OperationDescriptionCode Snippet
callForEachPerform action via function on each item$stream->callForEach($function)
consumeDrain stream, discarding values$stream->consume()
printprint each item in the stream$stream->print([$separator], [$prefix], [$suffix])
printLnprint each item on a new line$stream->printLn()
toCsvFileWrite the contents of the stream to a CSV file$stream->toCsvFile($fileHandle, [$headers])
toFileWrite the contents of the stream to a file$stream->toFile($fileHandle)

Stream Debug Operations

Debug OperationDescriptionCode Snippet
peekPeek at each element between stream operations$stream->peek($peekFunc)
peekStreamPeek at the entire stream between operations$stream->peekStream($peekFunc)
peekPrintPeek at each element by printing between operations$stream->peekPrint()
peekPrintRPeek at each element by doing print-r between operations$stream->peekPrintR()
printRprint_r each item$stream->printR()
varDumpvar_dump each item$stream->varDump()

Documentation

Full documentation with detailed descriptions, signatures, and code examples for each function.

Loop Iteration

Summarize and Reduce

  • Summary — AllMatch, AnyMatch, IsEmpty, IsSorted, and more
  • Reduce — ToAverage, ToSum, ToMin, ToMax, ToString, and more

Stream

  • Stream — Sources, operations, terminal operations, and debug tools

Usage

All functions work on iterable collections:

  • array (type)
  • Generator (type)
  • Iterator (interface)
  • Traversable (interface)

Composition

IterTools can be combined to create new iterable compositions.

Zip Strings

use IterTools\Multi;
use IterTools\Single;

$letters = 'ABCDEFGHI';
$numbers = '123456789';

foreach (Multi::zip(Single::string($letters), Single::string($numbers)) as [$letter, $number]) {
     $battleshipMove = new BattleshipMove($letter, $number)
}
// A1, B2, C3

Chain Strings

use IterTools\Multi;
use IterTools\Single;

$letters = 'abc';
$numbers = '123';

foreach (Multi::chain(Single::string($letters), Single::string($numbers)) as $character) {
    print($character);
}
// a, b, c, 1, 2, 3

Strict and Coercive Types

When there is an option, the default will do strict type comparisons:

  • scalars: compares strictly by type
  • objects: always treats different instances as not equal to each other
  • arrays: compares serialized

When type coercion (non-strict types) is available and enabled via optional flag:

  • scalars: compares by value via type juggling
  • objects: compares serialized (throws \InvalidArgumentException if the object cannot be serialized)
  • arrays: compares serialized

Standards

IterTools PHP conforms to the following standards:

License

IterTools PHP is licensed under the MIT License.

Similar Libraries in Other Languages

IterTools functionality is not limited to PHP and Python. Other languages have similar libraries. Familiar functionality is available when working in other languages.