forked from muglug/psl
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathflip.php
42 lines (36 loc) · 850 Bytes
/
flip.php
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
<?php
declare(strict_types=1);
namespace Psl\Dict;
use Psl;
use Psl\Type;
/**
* Flips the keys and values of an iterable.
*
* In case of duplicate values, later keys will overwrite the previous ones.
*
* Examples:
*
* Dict\flip(['a' => 1, 'b' => 2, 'c' => 3])
* => Dict(1 => 'a', 2 => 'b', 3 => 'c')
*
* @template Tk of array-key
* @template Tv of array-key
*
* @param iterable<Tk, Tv> $iterable
*
* @return array<Tv, Tk>
*/
function flip(iterable $iterable): array
{
$result = [];
foreach ($iterable as $key => $value) {
Psl\invariant(
Type\array_key()->matches($value),
'Expected all values to be of type array-key, value of type (%s) provided.',
gettype($value)
);
/** @var Tv $value */
$result[$value] = $key;
}
return $result;
}