Array Functions

This page is about the Nette\Utils\Arrays, ArrayHash and ArrayList classes, which are related to arrays.

Installation:

composer require nette/utils

Arrays

Nette\Utils\Arrays is a static class, which contains a handful of handy array functions. Its equivalent for iterators is Nette\Utils\Iterables.

Following examples assume the following class alias is defined:

use Nette\Utils\Arrays;

associate (array $array, mixed $path): array|\stdClass

The function flexibly transforms the $array into an associative array or objects according to the specified path $path. The path can be a string or an array. It consists of the names of keys in the input array and operators like ‘[]’, ‘->’, ‘=’, and ‘|’. Throws Nette\InvalidArgumentException if the path is invalid.

// converting to an associative array using a simple key
$arr = [
    ['name' => 'John', 'age' => 11],
    ['name' => 'Mary', 'age' => null],
    // ...
];
$result = Arrays::associate($arr, 'name');
// $result = ['John' => ['name' => 'John', 'age' => 11], 'Mary' => ['name' => 'Mary', 'age' => null]]
// assigning values from one key to another using the = operator
$result = Arrays::associate($arr, 'name=age'); // or ['name', '=', 'age']
// $result = ['John' => 11, 'Mary' => null, ...]
// creating an object using the -> operator
$result = Arrays::associate($arr, '->name'); // or ['->', 'name']
// $result = (object) ['John' => ['name' => 'John', 'age' => 11], 'Mary' => ['name' => 'Mary', 'age' => null]]
// combining keys using the | operator
$result = Arrays::associate($arr, 'name|age'); // or ['name', '|', 'age']
// $result: ['John' => ['name' => 'John', 'age' => 11], 'Paul' => ['name' => 'Paul', 'age' => 44]]
// adding to an array using []
$result = Arrays::associate($arr, 'name[]'); // or ['name', '[]']
// $result: ['John' => [['name' => 'John', 'age' => 22], ['name' => 'John', 'age' => 11]]]

contains (array $array, $value)bool

Tests an array for the presence of value. Uses a strict comparison (===)

Arrays::contains([1, 2, 3], 1);    // true
Arrays::contains(['1', false], 1); // false

every (array $array, callable $predicate)bool

Tests whether all elements in the array pass the test implemented by the provided function, which has the signature function ($value, $key, array $array): bool.

$array = [1, 30, 39, 29, 10, 13];
$isBelowThreshold = fn($value) => $value < 40;
$res = Arrays::every($array, $isBelowThreshold); // true

See some().

filter (array $array, callable $predicate)array

Returns a new array containing all key-value pairs matching the given $predicate. The callback has the signature function ($value, int|string $key, array $array): bool.

Arrays::filter(
	['a' => 1, 'b' => 2, 'c' => 3],
	fn($v) => $v < 3,
);
// ['a' => 1, 'b' => 2]

first (array $array, ?callable $predicate=null, ?callable $else=null)mixed

Returns the first item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null. The $predicate has the signature function ($value, int|string $key, array $array): bool.

It does not change the internal pointer unlike reset(). The $predicate and $else parameters exist since version 4.0.4.

Arrays::first([1, 2, 3]);                   // 1
Arrays::first([1, 2, 3], fn($v) => $v > 2); // 3
Arrays::first([]);                          // null
Arrays::first([], else: fn() => false);     // false

See last().

firstKey (array $array, ?callable $predicate=null): int|string|null

Returns the key of first item (matching the specified predicate if given) or null if there is no such item. The $predicate has the signature function ($value, int|string $key, array $array): bool.

Arrays::firstKey([1, 2, 3]);                   // 0
Arrays::firstKey([1, 2, 3], fn($v) => $v > 2); // 2
Arrays::firstKey(['a' => 1, 'b' => 2]);        // 'a'
Arrays::firstKey([]);                          // null

See lastKey().

flatten (array $array, bool $preserveKeys=false)array

Transforms multidimensional array to flat array.

$array = Arrays::flatten([1, 2, [3, 4, [5, 6]]]);
// $array = [1, 2, 3, 4, 5, 6];

get (array $array, string|int|array $key, ?mixed $default=null)mixed

Returns $array[$key] item. If it does not exist, Nette\InvalidArgumentException is thrown, unless a default value is set as third argument.

// if $array['foo'] does not exist, throws an exception
$value = Arrays::get($array, 'foo');

// if $array['foo'] does not exist, returns 'bar'
$value = Arrays::get($array, 'foo', 'bar');

Argument $key may as well be an array.

$array = ['color' => ['favorite' => 'red'], 5];

$value = Arrays::get($array, ['color', 'favorite']);
// returns 'red'

getRef (array &$array, string|int|array $key)mixed

Gets reference to given $array[$key]. If the index does not exist, new one is created with value null.

$valueRef = & Arrays::getRef($array, 'foo');
// returns $array['foo'] reference

Works with multidimensional arrays as well as get().

$value = & Arrays::get($array, ['color', 'favorite']);
// returns $array['color']['favorite'] reference

grep (array $array, string $pattern, bool $invert=false)array

Returns only those array items, which matches a regular expression $pattern. If $invert is true, it returns elements that do not match. Regex compilation or runtime error throws Nette\RegexpException.

$filteredArray = Arrays::grep($array, '~^\d+$~');
// returns only numerical items

insertAfter (array &$array, string|int|null $key, array $inserted)void

Inserts the contents of the $inserted array into the $array immediately after the $key. If $key is null (or does not exist), it is inserted at the end.

$array = ['first' => 10, 'second' => 20];
Arrays::insertAfter($array, 'first', ['hello' => 'world']);
// $array = ['first' => 10, 'hello' => 'world', 'second' => 20];

insertBefore (array &$array, string|int|null $key, array $inserted)void

Inserts the contents of the $inserted array into the $array before the $key. If $key is null (or does not exist), it is inserted at the beginning.

$array = ['first' => 10, 'second' => 20];
Arrays::insertBefore($array, 'first', ['hello' => 'world']);
// $array = ['hello' => 'world', 'first' => 10, 'second' => 20];

invoke (iterable $callbacks, …$args)array

Invokes all callbacks and returns array of results.

$callbacks = [
	'+' => fn($a, $b) => $a + $b,
	'*' => fn($a, $b) => $a * $b,
];

$array = Arrays::invoke($callbacks, 5, 11);
// $array = ['+' => 16, '*' => 55];

invokeMethod (iterable $objects, string $method, …$args)array

Invokes method on every object in an array and returns array of results.

$objects = ['a' => $obj1, 'b' => $obj2];

$array = Arrays::invokeMethod($objects, 'foo', 1, 2);
// $array = ['a' => $obj1->foo(1, 2), 'b' => $obj2->foo(1, 2)];

isList (array $array): bool

Checks if the array is indexed in ascending order of numeric keys from zero, a.k.a list.

Arrays::isList(['a', 'b', 'c']); // true
Arrays::isList([4 => 1, 2, 3]); // false
Arrays::isList(['a' => 1, 'b' => 2]); // false

last (array $array, ?callable $predicate=null, ?callable $else=null)mixed

Returns the last item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null. The $predicate has the signature function ($value, int|string $key, array $array): bool.

It does not change the internal pointer unlike end(). The $predicate and $else parameters exist since version 4.0.4.

Arrays::last([1, 2, 3]);                   // 3
Arrays::last([1, 2, 3], fn($v) => $v < 3); // 2
Arrays::last([]);                          // null
Arrays::last([], else: fn() => false);     // false

See first().

lastKey (array $array, ?callable $predicate=null): int|string|null

Returns the key of last item (matching the specified predicate if given) or null if there is no such item. The $predicate has the signature function ($value, int|string $key, array $array): bool.

Arrays::lastKey([1, 2, 3]);                    // 2
Arrays::lastKey([1, 2, 3], fn($v) => $v < 3);  // 1
Arrays::lastKey(['a' => 1, 'b' => 2]);         // 'b'
Arrays::lastKey([]);                           // null

See firstKey().

map (array $array, callable $transformer)array

Calls $transformer on all elements in the array and returns the array of return values. The callback has the signature function ($value, $key, array $array): bool.

$array = ['foo', 'bar', 'baz'];
$res = Arrays::map($array, fn($value) => $value . $value);
// $res = ['foofoo', 'barbar', 'bazbaz']

mapWithKeys (array $array, callable $transformer)array

Creates a new array by transforming the values and keys of the original array. The function $transformer has the signature function ($value, $key, array $array): ?array{$newValue, $newKey}. If $transformer returns null, the element is skipped. For retained elements, the first element of the returned array is used as the new key and the second element as the new value.

$array = ['a' => 1, 'b' => 2, 'c' => 3];
$result = Arrays::mapWithKeys($array, fn($v, $k) => $v > 1 ? [$v * 2, strtoupper($k)] : null);
// [4 => 'B']

This method is useful in situations where you need to change the structure of an array (both keys and values simultaneously) or filter elements during transformation (by returning null for unwanted elements).

mergeTree (array $array1, array $array2)array

Recursively merges two fields. It is useful, for example, for merging tree structures. It behaves as the + operator for array, ie. it adds a key/value pair from the second array to the first one and retains the value from the first array in the case of a key collision.

$array1 = ['color' => ['favorite' => 'red'], 5];
$array2 = [10, 'color' => ['favorite' => 'green', 'blue']];

$array = Arrays::mergeTree($array1, $array2);
// $array = ['color' => ['favorite' => 'red', 'blue'], 5];

Values from the second array are always appended to the first. The disappearance of the value 10 from the second array may seem a bit confusing. It should be noted that this value as well as the value 5 in the first array have the same numeric key 0, so in the resulting field there is only an element from the first array.

normalize (array $array, ?string $filling=null)array

Normalizes array to associative array. Replace numeric keys with their values, the new value will be $filling.

$array = Arrays::normalize([1 => 'first', 'a' => 'second']);
// $array = ['first' => null, 'a' => 'second'];
$array = Arrays::normalize([1 => 'first', 'a' => 'second'], 'foobar');
// $array = ['first' => 'foobar', 'a' => 'second'];

pick (array &$array, string|int $key, ?mixed $default=null)mixed

Returns and removes the value of an item from an array. If it does not exist, it throws an exception, or returns $default, if provided.

$array = [1 => 'foo', null => 'bar'];
$a = Arrays::pick($array, null);
// $a = 'bar'
$b = Arrays::pick($array, 'not-exists', 'foobar');
// $b = 'foobar'
$c = Arrays::pick($array, 'not-exists');
// throws Nette\InvalidArgumentException

renameKey (array &$array, string|int $oldKey, string|int $newKey)bool

Renames a key. Returns true if the key was found in the array.

$array = ['first' => 10, 'second' => 20];
Arrays::renameKey($array, 'first', 'renamed');
// $array = ['renamed' => 10, 'second' => 20];

getKeyOffset (array $array, string|int $key)?int

Returns zero-indexed position of given array key. Returns null if key is not found.

$array = ['first' => 10, 'second' => 20];
$position = Arrays::getKeyOffset($array, 'first'); // returns 0
$position = Arrays::getKeyOffset($array, 'second'); // returns 1
$position = Arrays::getKeyOffset($array, 'not-exists'); // returns null

some (array $array, callable $predicate)bool

Tests whether at least one element in the array passes the test implemented by the provided callback with signature function ($value, $key, array $array): bool.

$array = [1, 2, 3, 4];
$isEven = fn($value) => $value % 2 === 0;
$res = Arrays::some($array, $isEven); // true

See every().

toKey (mixed $key): string|int

Converts a value to an array key, which is either an integer or a string.

Arrays::toKey('1');  // 1
Arrays::toKey('01'); // '01'

toObject (iterable $array, object $object)object

Copies the elements of the $array array to the $object object and then returns it.

$obj = new stdClass;
$array = ['foo' => 1, 'bar' => 2];
Arrays::toObject($array, $obj); // it sets $obj->foo = 1; $obj->bar = 2;

wrap (array $array, string $prefix='', string $suffix='')array

It casts each element of array to string and encloses it with $prefix and $suffix.

$array = Arrays::wrap(['a' => 'red', 'b' => 'green'], '<<', '>>');
// $array = ['a' => '<<red>>', 'b' => '<<green>>'];

ArrayHash

Object Nette\Utils\ArrayHash is the descendant of generic class stdClass and extends it to the ability to treat it as an array, for example, accessing members using square brackets:

$hash = new Nette\Utils\ArrayHash;
$hash['foo'] = 123;
$hash->bar = 456; // also works object notation
$hash->foo; // 123

You can use the count($hash) function to get the number of elements.

You can iterate over an object as you would an array, even with a reference:

foreach ($hash as $key => $value) {
	// ...
}

foreach ($hash as $key => &$value) {
	$value = 'new value';
}

Existing arrays can be transformed to ArrayHash using from():

$array = ['foo' => 123, 'bar' => 456];

$hash = Nette\Utils\ArrayHash::from($array);
$hash->foo; // 123
$hash->bar; // 456

The transformation is recursive:

$array = ['foo' => 123, 'inner' => ['a' => 'b']];

$hash = Nette\Utils\ArrayHash::from($array);
$hash->inner; // object ArrayHash
$hash->inner->a; // 'b'
$hash['inner']['a']; // 'b'

It can be avoided by the second parameter:

$hash = Nette\Utils\ArrayHash::from($array, false);
$hash->inner; // array

Transform back to the array:

$array = (array) $hash;

ArrayList

Nette\Utils\ArrayList represents a linear array where the indexes are only integers ascending from 0.

$list = new Nette\Utils\ArrayList;
$list[] = 'a';
$list[] = 'b';
$list[] = 'c';
// ArrayList(0 => 'a', 1 => 'b', 2 => 'c')
count($list); // 3

You can use the count($list) function to get the number of items.

You can iterate over an object as you would an array, even with a reference:

foreach ($list as $key => $value) {
	// ...
}

foreach ($list as $key => &$value) {
	$value = 'new value';
}

Existing arrays can be transformed to ArrayList using from():

$array = ['foo', 'bar'];
$list = Nette\Utils\ArrayList::from($array);

Accessing keys beyond the allowed values throws an exception Nette\OutOfRangeException:

echo $list[-1]; // throws Nette\OutOfRangeException
unset($list[30]); // throws Nette\OutOfRangeException

Removing the key will result in renumbering the elements:

unset($list[1]);
// ArrayList(0 => 'a', 1 => 'c')

You can add a new element to the beginning using prepend():

$list->prepend('d');
// ArrayList(0 => 'd', 1 => 'a', 2 => 'c')
version: 4.0 3.x 2.x