Array Functions

Arrays

Nette\Utils\Arrays is a static class, which contains a handful of handy array functions.

Following examples assume the following class alias is defined:

use Nette\Utils\Arrays;

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 return 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 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, int $flags=null): array

Returns only those array items, which matches a regular expression $pattern. Regex compilation or runtime error throw Nette\RegexpException.

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

Value PREG_GREP_INVERT may be set as $flags, which inverts the selection.

searchKey(array $array, string|int $key): int

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

$array = ['first' => 10, 'second' => 20];
$position = Arrays::searchKey($array, 'first'); // returns 0

Since version 3 it will return null instead of false.

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

Appends array $inserted after item with $key index. If such a $key does not exist, the array 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 $key, array $inserted): void

Prepends content of $inserted array into $array before item with $key index. If such a $key does not exist, the array is inserted at the beginning.

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

mergeTree(array $array1, array $array2): array

Merges two arrays recursively. Useful for combining tree structures. It behaves as the + operator applied to arrays, ie. it adds to keys/values of the second array to the the first one. In case of collision, values of first array are used.

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

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

Values from second array are always appended to the first. Though the disappearance of value 10 might be confusing, it's fine – both 5 of the first array and the 10 do have same key 0.

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

Renames a key.

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

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

Transform multidimensional array to flat array.

$array = Arrays::flatten([
    2 => ['a', ['b']],
    4 => ['c', 'd'],
    'e',
]);
// $array = ['a', 'b', 'c', 'd', 'e'];

isList(array $array): bool

Check if the array is indexed by numeric keys in ascending series from zero.

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

normalize(array $arr, string $filling=null): array

Replace numeric keys in array to the value from variable $filling.

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

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

Returns and removes value of the item in array or if not exist throw exception or return filled $default.

$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

some(array $arr, callable $callback): bool

Check if some item of the array go through condition in $callback.

$array = ['foo', 'bar', 'baz'];
// have some bar???
$res = Arrays::some($array, function ($value, $key, $arr) { return $v === 'bar'; });
// $res = true

every(array $arr, callable $callback): bool

Check if all items of the array go through condition in $callback.

$array = ['foo', 'bar', 'baz'];
// have only bar???
$res = Arrays::some($array, function ($value, $key, $arr) { return $v === 'bar'; });
// $res = false

map(array $arr, callable $callback): array

Apply $callback to the all items in array and return results.

$array = ['foo', 'bar', 'baz'];
$res = Arrays::map($array, function ($value, $key, $arr) { return $v . $v; });
// $res = ['foofoo', 'barbar', 'bazbaz']

ArrayHash

Object Nette\Utils\ArrayHash is the descendant of an anonymous 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
echo $hash->foo; // 123

You can use count() and iterate over the object, as in the case of the array:

echo count($hash); // 2

foreach ($hash as $key => $value) ...

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

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

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

The transformation is recursive, which can be avoided by the second parameter:

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

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')
echo count($list); // 3

Over the object you can iterate or call count(), as in the case of a 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:

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

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

$list->prepend('d');
// ArrayList(0 => 'd', 1 => 'a', 2 => 'c')