PHPackages                             nixn/php-util - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. nixn/php-util

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

nixn/php-util
=============

PHP language utilities, mostly to code more in functional style, but also other stuff.

v1.2(7mo ago)0141MITPHPPHP &gt;=8.2CI passing

Since Jan 18Pushed 6mo ago1 watchersCompare

[ Source](https://github.com/nixn/php-util)[ Packagist](https://packagist.org/packages/nixn/php-util)[ RSS](/packages/nixn-php-util/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (1)Versions (4)Used By (1)

php-util
========

[](#php-util)

A PHP library with utility functions, mostly useful when coding in functional style, but also some other stuff.

[![GitHub License](https://camo.githubusercontent.com/05d76d8bb93263b7cbaee602bd6007a55d04a1ba681931339a2f70262dbfdbb5/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6e69786e2f7068702d7574696c)](https://camo.githubusercontent.com/05d76d8bb93263b7cbaee602bd6007a55d04a1ba681931339a2f70262dbfdbb5/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6e69786e2f7068702d7574696c)[![Quality Assurance](https://github.com/nixn/php-util/actions/workflows/quality-assurance.yml/badge.svg)](https://github.com/nixn/php-util/actions/workflows/quality-assurance.yml)[![codecov](https://camo.githubusercontent.com/7c82bdfcd556ec50f952a00f728bfaf9002019cd76a1dd15569a515bce32d831/68747470733a2f2f636f6465636f762e696f2f6769746875622f6e69786e2f7068702d7574696c2f67726170682f62616467652e7376673f746f6b656e3d494439494c3353334850)](https://codecov.io/github/nixn/php-util)[![Packagist Version](https://camo.githubusercontent.com/b4d801658079e9a5af4a7aa651ffcfb6f480e39f827ee97192d8b8fe2809550f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e69786e2f7068702d7574696c)](https://packagist.org/packages/nixn/php-util)[![Packagist Downloads](https://camo.githubusercontent.com/e6c0790b7eb8720f4143796a310129dc4c170e044037b2ef7ac80ce2d0b19b46/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e69786e2f7068702d7574696c3f636f6c6f723d626c7565)](https://packagist.org/packages/nixn/php-util)[![Packagist Dependency Version](https://camo.githubusercontent.com/dc231ea2c2c8c7d68202d55ff32d60e20041327787324d775aed958c3312f863/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646570656e64656e63792d762f6e69786e2f7068702d7574696c2f706870)](https://camo.githubusercontent.com/dc231ea2c2c8c7d68202d55ff32d60e20041327787324d775aed958c3312f863/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646570656e64656e63792d762f6e69786e2f7068702d7574696c2f706870)[![API docs](https://camo.githubusercontent.com/605bb29a0fdf33de97f33e40c19dd6d6735b29e6833b0daf5047c064c7827473/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4150492d646f63732d626c7565)](https://nixn.github.io/php-util/namespaces/nixn-php.html)

Installation
------------

[](#installation)

Via composer:

```
composer require nixn/php-util

```

Documentation
-------------

[](#documentation)

See the [API docs](https://nixn.github.io/php-util/namespaces/nixn-php.html).

The (only) namespace is `nixn\php`. All functions (except in the wrappers [`Pipe`](https://nixn.github.io/php-util/classes/nixn-php-Pipe.html) and [`With`](https://nixn.github.io/php-util/classes/nixn-php-With.html)) are static, so they can be called easily (e.g. [`Arr::pick($array, 'a', 'b')`](https://nixn.github.io/php-util/classes/nixn-php-Arr.html#method_pick)).

Components
----------

[](#components)

### [Arr (ay)](https://nixn.github.io/php-util/classes/nixn-php-Arr.html)

[](#arr-ay)

- `pick(array $array, string|int ...$keys): array`
    Returns a new array with only the key =&gt; value mappings left, whose keys are in $keys.

```
$array = ['a' => 'A', 'b' => 'B', 1 => 'one', 2 => 'two'];
Arr::pick($array, 'a', 2) // => ['a' => 'A', 2 => 'two']
```

- `find_by(array $array, callable $predicate, bool $return_key = false): mixed`
    Searches for a value in the array, based on the predicate, returning it (or its key) or null, when not found.

```
$array = ['a' => 'A', 'b' => 'B', 1 => 'one', 2 => 'two'];
$predicate = fn($v, $k) => is_int($k) && $k % 2 == 0;
Arr::find_by($array, $predicate) // => 'two'
Arr::find_by($array, $predicate, true) // => 2
```

- `reduce(iterable $iterable, callable $callback, mixed $initial = , bool $on_empty = false): mixed`
    Like array\_reduce(), but the callback passes the key of the element, too. Also, more control over the return value.

```
$array = ['a' => 'A', 'b' => 'B', 1 => 'one', 2 => 'two'];
$callback = fn($carry, $v, $k) => "$carry|$k";
Arr::reduce($array, $callback, "") // => "|a|b|1|2"
```

- `kvjoin(iterable $iterable, string $sep = ', ', string $kv_sep = '='): string`
    Like implode()/join() in legacy syntax, but outputs the keys too and takes an additional parameter `$kv_sep`.

```
$array = ['a' => 'A', 'b' => 'B', 1 => 'one', 2 => 'two'];
Arr::kvjoin($array) // => "a=A, b=B, 1=one, 2=two"
```

- `first(iterable $iterable): array`
    Returns the first mapping (element) of an array as key and value in an array, or null/null if the array is empty.

```
$array = ['a' => 'A', 'b' => 'B', 1 => 'one', 2 => 'two'];
Arr::first($array) // => ['k' => 'a', 'v' => 'A']
Arr::first([]) // => ['k' => null, 'v' => null]
```

- `find(array $array, string|int ...$ks): array`
    Searches for a mapping in the array whose key is one of $keys, returns the key and the value or null/null (if not found) as an array.

```
$array = ['a' => 'A', 'b' => 'B', 1 => 'one', 2 => 'two'];
Arr::find($array, 'b', 1) // => ['k' => 'b', 'v' => 'B']
Arr::find($array, 'c', 1) // => ['k' => 1, 'v' => 'one']
Arr::find($array, 'c', 3) // => ['k' => null, 'v' => null]
```

The return value for the last two functions is well suited for array destruction and safety on searching:

```
['k' => $key, 'v' => $value] = Arr::find($array, 2, 'b');
if ($key === null)
    echo "Not Found";
else
    echo "Found value $value with key $key";
// prints: Found value two with key 2
```

### [Partial](https://nixn.github.io/php-util/classes/nixn-php-Partial.html)

[](#partial)

- `partial(callable $callable, mixed ...$args): callable`
    Returns a new function, which will call the callable with the provided args and can use placeholders for runtime args.

```
$comment_match = Partial::partial(preg_match(...), '/^\\s*(?:#|$)/');
$comment_match('# comment line') // => 1
$comment_match('normal line') // => 0

$keyword_match = Partial::partial(preg_match(...), '/php/i', Partial::PLACEHOLDER, null, 0, Partial::PLACEHOLDER);
$keyword_match('Only PHP makes this possible!', 0) // => 1
$keyword_match('Only PHP makes this possible!', 10) // => 0
```

### Str (ing)

[](#str-ing)

- `trim_prefix(string $string, string $prefix): string`
    Trims a string prefix when it matches.

```
$str = "abcdef";
Str::trim_prefix($str, 'abc') // => "def"
Str::trim_prefix($str, 'def') // => "abcdef"
```

- `trim_suffix(string $string, string $suffix): string`
    Trims a string suffix when it matches.

```
$str = "abcdef";
Str::trim_suffix($str, 'abc') // => "abcdef"
Str::trim_suffix($str, 'def') // => "abc"
```

### [Util](https://nixn.github.io/php-util/classes/nixn-php-Util.html)

[](#util)

- `identity(mixed $v): mixed`
    Just returns the input value. Useful in functional programming style.

```
Util::identity(42) // => 42
```

- `map(mixed $v, ?callable $fn = null, bool $null_on_not = false, bool $func = false, bool $null = true, bool $false = false, bool $empty = false, bool $zero = false): mixed`
    Checks `$v` on (selectable) common falsy values and returns `$fn($v)` or `$v` (when `$fn === null`) when not falsy. Returns `$v` or null otherwise (depending on `$null_on_not`).

```
$parenthesize = fn($x) => "($x)";
Util::map(0, $parenthesize) // => "(0)"
Util::map(0, $parenthesize, zero: true) // => 0
Util::map(0, $parenthesize, null_on_not: true, zero: true) // => null
Util::map(42, null, func: true) // => 42
Util::map(42, null, null_on_not: true, func: true) // => null
```

- `map_nots(mixed $v, ?callable $fn = null, bool $null_on_not = false, bool $func = false, mixed ... $nots): mixed`
    Like `map()`, but the falsy values are given as arguments (`$nots`).

```
$parenthesize = fn($x) => "($x)";
Util::map_nots(42, $parenthesize, false, false, 42) // => 42
Util::map_nots(42, $parenthesize, true, false, 42) // => null
Util::map_nots(null, $parenthesize, true, false, 42) // => "()"
```

- `when(mixed $test, mixed $v, ?callable $fn = null, bool $null = true, bool $false = true, bool $empty = false, bool $zero = false): mixed`
    Returns a value based on `$test`, `$v` and `$fn`, testing based on selectable common falsy values. (See PHPdoc for more information.)

```
$parenthesize = fn($x) => "($x)";
Util::when(false, rand(...), $parenthesize) // => null (rand() not executed)
Util::when(true, rand(...), $parenthesize) // => "(42)"
Util::when(9, sqrt(...)) // => 3 (same as Util::map(9, sqrt(...)) or even just sqrt(9))
Util::when($get_from_database, fn() => $db->get(), fn($result) => $result->deep_value()) // the natural use case of this
Util::when($use_title, fn() => ['title', $this->title], Hiccup::html(...)) // the natural use case for this
Util::when(get_title(), fn($title) => ['title', $title], Hiccup::html(...), empty: true)
```

- `when_nots(mixed $test, mixed $v, ?callable $fn = null, mixed ... $nots): mixed`
    Like `when()`, but the falsy values are given as arguments (`$nots`).
- `tree_path(mixed $element, callable $get_parent, ?callable $while = null): \Generator`
    For any node in a tree structure, get all parents (possibly up to a specific one) and return them from top to bottom.

```
$leaf = new Node('c', parent: new Node('b', parent: new Node('a')));
foreach (Util::tree_path($leaf, fn($node) => $node->parent) as $node)
    echo "$node->name,";
// prints: a,b,c,
foreach (Util::tree_path($leaf, fn($node) => $node->parent, fn($node) => $node->name !== 'a') as $node)
    echo "$node->name,";
// prints: b,c,
```

- `new(string $class): \Closure`
    Returns a Closure for a constructor call.

```
$new_color = Util::new(Color::class);
$color = $new_color(0, 127, 255); // $color instanceof Color
```

### [Pipe](https://nixn.github.io/php-util/classes/nixn-php-Pipe.html)

[](#pipe)

A `Pipe` object wraps an intial value and pipes it through any function which modifies it. The resulting value can be accessed at the end.

Example:

```
