A PHP functional utility library, port of Javascript Lodash/Fp and Ramda libraries to PHP.
All functions are side-effect free and automatically curried, data is immutable.
The iterable collection parameter is usually supplied last to make currying convenient.
Lazy / delayed evaluation is supported in functional pipelines.
Go to https://idlephp.tech for more details, documentation and examples.
PHP 8.4 or higher
composer require miroshnikov/idles
Note
Idles is currently under active development. Roadmap is to add all methods from Lodash and Ramda libraries and some functional tools.
add($a, $b)Calculates the sum of two numbers.
all($predicate, $collection)Checks if $predicate returns truthy for all elements of $collection. Stop once it returns falsey.
allPass($predicates)Returns a function that checks if its arguments pass all $predicates.
always($value)Returns a function that always returns the given value.
any($predicate, $collection)Checks if $predicate returns truthy for any element of $collection. Stops on first found.
anyPass($predicates)Returns a function that checks if its arguments pass any of the $predicates.
apply($fn, $args)Calls $fn(...$args)
applyTo($value, $interceptor)Returns the result of $interceptor($value).
ary($n, $fn)Creates a function that invokes $fn, with up to $n arguments, ignoring any additional arguments.
ascend($fn, $a, $b)Makes an ascending comparator function out of a function that returns a value that can be compared with <=>.
attempt($fn, $args)Calls $fn, returning either the result or the caught exception.
both($fn1, $fn2)Resulting function returns $fn1(...$args) if it is falsy or $fn2(...$args) otherwise, short-circuited.
camelCase($s)Converts string to camel case.
capitalize($string)Converts the first character of string to upper case and the remaining to lower case.
collect($collection)Collects any iterable into array
compose(...$fns)Like pipe but invokes the functions from right to left.
concat($iterable, $value)Concatinates an iterable with an iterable/value.
concatAll($values)Concatinates an iterable with additional iterables/values
cond($pairs)Iterates over $pairs and invokes the corresponding function of the first predicate to return truthy.
count($predicate, $collection)Counts the number of items in $collection matching the $predicate
countBy($iteratee, $collection)Returns an array<result of $iteratee($value), number of times the $iteratee($value) was found in $collection>
curry($fn)\Idles\_ const may be used as a placeholder.
curryN($arity, $fn)Curry with fixed arity. \Idles\_ const may be used as a placeholder.
curryRight($f)Like curry but arguments are prepended.
curryRightN($arity, $f)Like curryN but arguments are prepended.
dec($number)Returns $number - 1
defaultTo($default, $value)Returns the first argument if it is truthy, otherwise the second argument.
descend($fn, $a, $b)Makes an descending comparator function out of a function that returns a value that can be compared with <=>.
divide($a, $b)Returns $a / $b
drop($n, $collection)Skips the first $n elemens and returns the rest of iterable or string.
dropLast($n, $collection)Skips the last $n elements of iterable or string.
each($iteratee, $collection)Iterates over elements of $collection. Iteratee may exit iteration early by returning false.
either($fn1, $fn2)Resulting function returns $fn1(...$args) if it is truthy or $fn2(...$args) otherwise, short-circuited.
eq($a, $b)$a == $b
equals($a, $b)$a === $b
escapeRegExp($s)Escapes regular expression.
evolve($transformations, $record)Creates a new record by recursively calling transformation functions with $record properties.
F(...$args)Always returns false
filter($predicate, $collection)Returns elements $predicate returns truthy for.
find($predicate, $collection)Returns the first element $predicate returns truthy for.
findFrom($predicate, $fromIndex, $collection)Returns the first element $predicate returns truthy for starting from $fromIndex.
findIndex($predicate, $collection)Returns the index of the first element predicate returns truthy for or -1 if not found.
findIndexFrom($predicate, $fromIndex, $collection)Returns the index of the first element $predicate returns truthy for starting from $fromIndex.
findLastIndex($predicate, $collection)Returns the index of the last element predicate returns truthy for, -1 if not found.
findLastIndexFrom($predicate, $fromIndex, $collection)Returns the index of the last element $predicate returns truthy for starting from $fromIndex.
flatMap($iteratee, $collection)Maps and flattens.
flatMapDepth($iteratee, $depth, $collection)Maps and flattens the mapped results up to $depth times.
flatten($collection)Flattens iterable a single level deep.
flattenDepth($depth, $collection)Recursively flatten array up to $depth times.
flip($fn)Returns a new curried function with the first two arguments reversed.
flow($funcs)Left-to-right function composition. The first argument may have any arity; the remaining arguments must be unary.
fromPairs($collection)Creates a new record from a list key-value pairs. The inverse of toPairs.
groupBy($iteratee, $collection)Creates an array composed of keys generated from running each value through $iteratee.
gt($a, $b)$a > $b
gte($a, $b)$a >= $b
has($key, $record)Checks if $record has $key.
hasPath($path, $record)Checks if $path exists in $record.
head($collecton)Gets the first element of $collecton.
identity($value)Returns the first argument it receives.
ifElse($predicate, $onTrue, $onFalse)Resulting function returns $onTrue(...$args) if $predicate(...$args) is truthy or $onFalse(...$args) otherwise.
inc($number)Returns $number + 1
includes($value, $collection)Checks if $value is in iterable/string.
includesFrom($value, $fromIndex, $collection)Checks if $value is in iterable/string, starting from $fromIndex.
indexBy($iteratee, $collection)Creates a record composed of keys generated from the results of running each element of $collection through $iteratee.
indexOf($item, $collection)Returns the index of the first occurrence of the item in an iterable or string, else -1.
indexOfFrom($item, $fromIndex, $collection)Returns the index of the first occurrence of the item in an iterable or string, starting from $fromIndex, else -1.
intersection($array1, $array2)Returns unique values that are included in both arrays.
intersectionBy($iteratee, $array1, $array2)Like intersection but invokes $iteratee for each element before comparison.
intersectionWith($comparator, $array1, $array2)Like intersection but invokes $comparator to compare elements.
invert($collection)Replaces keys with values. Duplicate keys are overwritten.
iterate($fn, $value)Returns a generator of $value, $f($value), $f($f($value)) etc.
join($separator, $collection)Joins iterable elements separated by $separator.
just($value)Returns an Optional with the specified non-null value
juxt($iteratees)Applies a list of functions to a list of values.
keys($record)Returns an indexed iterable of keys in $record.
last($collecton)Gets the last element of iterable.
lastIndexOf($item, $collection)Returns the index of the last occurrence of $value in iterable or string, else -1.
length($value)Returns size of a countable, number of parameters of a function, lenght of string or number of properties of an object.
lt($a, $b)$a < $b
lte($a, $b)$a <= $b
map($iteratee, $collection)Run each element in $collection through $iteratee.
memoize($fn)Creates a function that memoizes the result of $fn.
memoizeWith($resolver, $fn)Creates a function that memoizes the result of $fn. $resolver returns map cache key (args[0] by default).
merge($left, $right)Merges properties, numeric keys are replaced.
mergeAll($iterables)Merges properties, numeric keys are replaced.
mergeDeep($left, $right)Merges properties recursively, numeric keys are replaced.
mergeWith($customizer, $left, $right)Like merge but if a key exists in both records, $customizer is called to the values associated with the key.
modifyPath($path, $updater, $record)Creates new record by applying an $updater function to the value at the given $path.
modulo($a, $b)$a % $b
multiply($a, $b)$a * $b
negate($predicate)Creates a function that negates the result of the $predicate function.
not($a)returns !$a
nothing()Returns an empty Optional.
now()Returns the timestamp of the number of seconds
nth($offset, $collection)Returns the $offset element. If $offset is negative the element at index length + $offset is returned.
nthArg($n)Returns a function which returns its $nth argument.
objOf($key, $value)Creates an array containing a single key => value pair.
omit($keys, $collection)The opposite of pick. Returns record without $keys.
omitBy($predicate, $collection)The opposite of pickBy. Returns properties of $record that $predicate returns falsey for.
once($fn)$fn is only called once, the first value is returned in subsequent invocations.
interface Optional
{
/**
* @return bool true if not empty
*/
public function isPresent(): bool;
/**
* @return bool true if empty
*/
public function isEmpty(): bool;
/**
* Returns value, throw exception if empty
*/
public function get(): mixed;
/**
* Returns the contained value if the optional is nonempty or `$default`
*/
public function orElse(mixed $default): mixed;
/**
* Returns the contained value, if present, otherwise throw an exception
*/
public function orElseThrow(\Exception $e = new \Exception('No value on None')): mixed;
/**
* If a value is present, apply the `$fn` to it, and if the result is non-null, return an Optional describing the result
*/
public function map(callable $fn): Optional;
/**
* Use instead of map if $f returns Optional
*/
public function flatMap(callable $fn): Optional;
/**
* If a value is present and matches the `$predicate`, return an Optional with the value, otherwise an empty Optional.
*/
public function filter(callable $predicate): Optional;
}Maybe/Option monad (container) which may or may not contain a non-null value.
orderBy($iteratees, $orders, $collection)Like sortBy but allows specifying the sort orders.
partial($fn, $partials)Creates a function that invokes $fn with $partials prepended to the arguments. \Idles\_ const may be used as a placeholder.
partialRight($fn, $partials)Like partial but $partials are appended.
partition($predicate, $collection)Split $collection into two groups, the first of which contains elements $predicate returns truthy for, the second of which contains elements $predicate returns falsey for.
path($path, $collection)Retrieve the value at a given path.
pathOr($default, $path, $collection)Retrieve the value at a given path. If path is not found, the $default is returned.
paths($paths, $collection)Keys in, values out. Order is preserved.
pick($keys, $collection)Returns record containing only $keys.
pickBy($predicate, $collection)Returns record containing only keys $predicate returns truthy for.
pipe(...$fns)Left-to-right function composition. The first argument may have any arity; the remaining arguments must be unary.
pluck($key, $collection)Returns a new array by plucking the same named property off all records in the array supplied.
project($props, $collection)Like SQL select statement.
prop($key, $record)Return the specified property.
propEq($key, $value, $record)Returns $record[$key] == $value
propOr($default, $key, $record)Return the $key property or $default.
rearg($indexes, $fn)Returns a curried function that invokes $fn with arguments rearranged according to $indexes.
reduce($iteratee, $accumulator, $collection)Reduces $collection to a value which is the accumulated result of running each element in collection through $iteratee.
remove($start, $count, $iterable)Removes items from $iterable starting at $start and containing $count elements.
resolve($resolvers, $record)Adds new properties to $record using $resolvers.
round($precision, $number)Rounds $number to specified $precision
setPath($path, $value, $record)Return copy of $record with $path set with $value.
slice($start, $end, $collection)Returns a slice of iterable or string from $start up to, but not including $end.
sort($comparator, $collection)Sorts $collection using $comparator comparison ($a <=> $b) function.
sortBy($iteratees, $collection)Sorts $collection in ascending order according to $comparators.
sortWith($comparators, $collection)Sorts a $collection according to an array of comparison ($a <=> $b) functions.
split($separator, $s)Splits string by $separator regular expression.
splitAt($index, $arrayOrString)Splits a given array or string at a given index.
splitEvery($length, $arrayOrString)Splits an array or string into slices of the specified length.
splitWhen($predicate, $iterable)Splits an array by predicate.
splitWhenever($predicate, $iterable)Splits an array into slices on every occurrence of a value.
startsWith($target, $s)If string starts with $target.
subtract($a, $b)$a - $b
sum($collection)Sums elements in $collection
sumBy($iteratee, $collection)Sums elements, $iteratee is invoked for each element in $collection to generate the value to be summed.
T(...$args)Always returns true
take($n, $collection)Takes $n first elements from iterable.
takeLast($n, $collection)Returns a slice of iterable with $n elements taken from the end.
tap($interceptor, $value)Calls $interceptor($value) then returns the original $value.
times($iteratee, $n)Calls the iteratee $n times, returning an array of the results of each invocation.
toLower($s)Converts string to lower case.
toPairs($record)Converts a record into an array of [$key, $value].
toUpper($s)Converts string to upper case.
trim($characters, $string)Strip characters from the beginning and end of a string.
trimEnd($characters, $string)Strip characters from the end of a string.
trimStart($characters, $string)Strip characters from the beginning of a string.
tryCatch($tryer, $catcher, $value)Calls $tryer, if it throws, calls $catcher.
unapply($fn)Returns fn (...$args) => $fn($args)
unary($fn)ary(1, $fn)
uniq($collection)Removes duplicates using ===.
uniqBy($iteratee, $collection)Like uniq but apply $iteratee fist.
uniqWith($predicate, $collection)Like uniq but uses $predicate to compare elements.
unless($predicate, $whenFalse, $value)Returns $predicate($value) ? $value : $whenFalse($value).
useWith($fn, $transformers)Applies each transformer function to each argument. Returns a new curried functions.
values($collection)Returns an indexed iterable of values in $collection.
when($predicate, $whenTrue, $value)Returns $predicate($value) ? $whenTrue($value) : $value.
where($spec, $record)Checks if $record satisfies the spec by invoking the $spec properties with the corresponding properties of $record.
whereAny($spec, $record)Checks if $record satisfies the spec by invoking the $spec properties with the corresponding properties of $record. Returns true if at least one of the predicates returns true.
whereEq($spec, $test)Check if the $test satisfies the $spec.
without($values, $collection)Returns $iterable without $values.
words($pattern, $s)Splits string into an array of its words.
zip($a, $b)Creates a new iterable out of the two supplied by pairing up equally-positioned items from both iterables.
zipAll($iterables)Same as zip but for many iterables.
zipWith($iteratee, $a, $b)Like zip except that it accepts $iteratee to specify how grouped values should be combined.