/
arrays.texy
333 lines (224 loc) Β· 9.55 KB
/
arrays.texy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
Array Functions
***************
.[perex]
This page is about the [Nette\Utils\Arrays|#Arrays], [#ArrayHash] and [#ArrayList] classes, which are related to arrays.
Installation:
```shell
composer require nette/utils
```
Arrays
======
[api:Nette\Utils\Arrays] is a static class, which contains a handful of handy array functions.
Following examples assume the following class alias is defined:
```php
use Nette\Utils\Arrays;
```
every(array $array, callable $callback): bool .[method]
-------------------------------------------------------
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`.
```php
$array = [1, 30, 39, 29, 10, 13];
$isBelowThreshold = function ($value) { return $value < 40; };
$res = Arrays::every($array, $isBelowThreshold); // true
```
See [#some()].
flatten(array $array, bool $preserveKeys=false): array .[method]
----------------------------------------------------------------
Transforms multidimensional array to flat array.
```php
$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 .[method]
------------------------------------------------------------------------------
Returns `$array[$key]` item. If it does not exist, `Nette\InvalidArgumentException` is thrown, unless a default value is set as third argument.
```php
// 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.
```php
$array = ['color' => ['favorite' => 'red'], 5];
$value = Arrays::get($array, ['color', 'favorite']);
// returns 'red'
```
getRef(array &$array, string|int|array $key): mixed .[method]
-------------------------------------------------------------
Gets reference to given `$array[$key]`. If the index does not exist, new one is created with value `null`.
```php
$valueRef = & Arrays::getRef($array, 'foo');
// returns $array['foo'] reference
```
Works with multidimensional arrays as well as [#get()].
```php
$value = & Arrays::get($array, ['color', 'favorite']);
// returns $array['color']['favorite'] reference
```
grep(array $array, string $pattern, int $flags=null): array .[method]
---------------------------------------------------------------------
Returns only those array items, which matches a regular expression `$pattern`. Regex compilation or runtime error throws `Nette\RegexpException`.
```php
$filteredArray = Arrays::grep($array, '~^\d+$~');
// returns only numerical items
```
Value `PREG_GREP_INVERT` may be set as `$flags`, which inverts the selection.
insertAfter(array &$array, string|int|null $key, array $inserted): void .[method]
---------------------------------------------------------------------------------
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.
```php
$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 .[method]
----------------------------------------------------------------------------------
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.
```php
$array = ['first' => 10, 'second' => 20];
Arrays::insertBefore($array, 'first', ['hello' => 'world']);
// $array = ['hello' => 'world', 'first' => 10, 'second' => 20];
```
isList(array $array): bool .[method]
------------------------------------
Checks if the array is indexed in ascending order of numeric keys from zero, a.k.a list.
```php
Arrays::isList(['a', 'b', 'c']); // true
Arrays::isList([4 => 1, 2, 3]); // false
Arrays::isList(['a' => 1, 'b' => 2]); // false
```
map(array $array, callable $callback): array .[method]
------------------------------------------------------
Calls `$callback` on all elements in the array and returns the array of return values. The callback has the signature `function ($value, $key, array $array): bool`.
```php
$array = ['foo', 'bar', 'baz'];
$res = Arrays::map($array, function ($value) { return $value . $value; });
// $res = ['foofoo', 'barbar', 'bazbaz']
```
mergeTree(array $array1, array $array2): array .[method]
--------------------------------------------------------
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.
```php
$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 .[method]
--------------------------------------------------------------
Normalizes array to associative array. Replace numeric keys with their values, the new value will be `$filling`.
```php
$array = Arrays::normalize([1 => 'first', 'a' => 'second']);
// $array = ['first' => null, 'a' => 'second'];
```
```php
$array = Arrays::normalize([1 => 'first', 'a' => 'second'], 'foobar');
// $array = ['first' => 'foobar', 'a' => 'second'];
```
pick(array &$array, string|int $key, mixed $default=null): mixed .[method]
--------------------------------------------------------------------------
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.
```php
$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): void .[method]
--------------------------------------------------------------------------------
Renames a key.
```php
$array = ['first' => 10, 'second' => 20];
Arrays::renameKey($array, 'first', 'renamed');
// $array = ['renamed' => 10, 'second' => 20];
```
searchKey(array $array, string|int $key) .[method]
--------------------------------------------------
Returns zero-indexed position of given array key. Returns `false` if key is not found.
```php
$array = ['first' => 10, 'second' => 20];
$position = Arrays::searchKey($array, 'first'); // returns 0
$position = Arrays::searchKey($array, 'second'); // returns 1
$position = Arrays::searchKey($array, 'not-exists'); // returns null
```
.[note]
Since version 3 it will return `null` instead of `false`.
some(array $array, callable $callback): bool .[method]
------------------------------------------------------
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`.
```php
$array = [1, 2, 3, 4];
$isEven = function ($value) { return $value % 2 === 0; };
$res = Arrays::some($array, $isEven); // true
```
See [#every()].
ArrayHash
=========
Object [api: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:
```php
$hash = new Nette\Utils\ArrayHash;
$hash['foo'] = 123;
$hash->bar = 456; // also works object notation
$hash->foo; // 123
```
You can use `count()` and iterate over the object, as in the case of the array:
```php
count($hash); // 2
foreach ($hash as $key => $value) // ...
```
Existing arrays can be transformed to `ArrayHash` using `from()`:
```php
$array = ['foo' => 123, 'bar' => 456];
$hash = Nette\Utils\ArrayHash::from($array);
$hash->foo; // 123
$hash->bar; // 456
```
The transformation is recursive:
```php
$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:
```php
$hash = Nette\Utils\ArrayHash::from($array, false);
$hash->inner; // array
```
Transform back to the array:
```php
$array = (array) $hash;
```
ArrayList
=========
[api:Nette\Utils\ArrayList] represents a linear array where the indexes are only integers ascending from 0.
```php
$list = new Nette\Utils\ArrayList;
$list[] = 'a';
$list[] = 'b';
$list[] = 'c';
// ArrayList(0 => 'a', 1 => 'b', 2 => 'c')
count($list); // 3
```
Over the object you can iterate or call `count()`, as in the case of an array.
Accessing keys beyond the allowed values throws an exception `Nette\OutOfRangeException`:
```php
echo $list[-1]; // throws Nette\OutOfRangeException
unset($list[30]); // throws Nette\OutOfRangeException
```
Removing the key will result in renumbering the elements:
```php
unset($list[1]);
// ArrayList(0 => 'a', 1 => 'c')
```
You can add a new element to the beginning using `prepend()`:
```php
$list->prepend('d');
// ArrayList(0 => 'd', 1 => 'a', 2 => 'c')
```