Skip to content

Commit 2bc2f58

Browse files
committed
added Arrays::first(), last() & contains()
1 parent 1dc0709 commit 2bc2f58

File tree

4 files changed

+87
-0
lines changed

4 files changed

+87
-0
lines changed

src/Utils/Arrays.php

+30
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,36 @@ public static function searchKey(array $array, $key): ?int
9999
}
100100

101101

102+
/**
103+
* Tests an array for the presence of value.
104+
* @param mixed $value
105+
*/
106+
public static function contains(array $array, $value): bool
107+
{
108+
return in_array($value, $array, true);
109+
}
110+
111+
112+
/**
113+
* Returns the first item from the array or null if array is empty.
114+
* @return mixed
115+
*/
116+
public static function first(array $array)
117+
{
118+
return count($array) ? reset($array) : null;
119+
}
120+
121+
122+
/**
123+
* Returns the last item from the array or null if array is empty.
124+
* @return mixed
125+
*/
126+
public static function last(array $array)
127+
{
128+
return count($array) ? end($array) : null;
129+
}
130+
131+
102132
/**
103133
* Inserts the contents of the $inserted array into the $array immediately after the $key.
104134
* If $key is null (or does not exist), it is inserted at the beginning.

tests/Utils/Arrays.contains().phpt

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Nette\Utils\Arrays;
6+
use Tester\Assert;
7+
8+
9+
require __DIR__ . '/../bootstrap.php';
10+
11+
12+
Assert::false(Arrays::contains([], 'a'));
13+
Assert::true(Arrays::contains(['a'], 'a'));
14+
Assert::true(Arrays::contains([1, 2, 'a'], 'a'));
15+
Assert::false(Arrays::contains([1, 2, 3], 'a'));
16+
Assert::false(Arrays::contains([1, 2, 3], '1'));

tests/Utils/Arrays.first().phpt

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Nette\Utils\Arrays;
6+
use Tester\Assert;
7+
8+
9+
require __DIR__ . '/../bootstrap.php';
10+
11+
12+
Assert::null(Arrays::first([]));
13+
Assert::null(Arrays::first([null]));
14+
Assert::false(Arrays::first([false]));
15+
Assert::same(1, Arrays::first([1, 2, 3]));
16+
17+
18+
$arr = [1, 2, 3];
19+
end($arr);
20+
Assert::same(1, Arrays::first($arr));
21+
Assert::same(3, current($arr));

tests/Utils/Arrays.last().phpt

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Nette\Utils\Arrays;
6+
use Tester\Assert;
7+
8+
9+
require __DIR__ . '/../bootstrap.php';
10+
11+
12+
Assert::null(Arrays::last([]));
13+
Assert::null(Arrays::last([null]));
14+
Assert::false(Arrays::last([false]));
15+
Assert::same(3, Arrays::last([1, 2, 3]));
16+
17+
18+
$arr = [1, 2, 3];
19+
Assert::same(3, Arrays::last($arr));
20+
Assert::same(1, current($arr));

0 commit comments

Comments
 (0)