friendship ended with social-app. php is my new best friend
1<?php
2/**
3 * Class Arrays
4 *
5 * @created 29.10.2024
6 * @author smiley <smiley@chillerlan.net>
7 * @copyright 2024 smiley
8 * @license MIT
9 */
10declare(strict_types=1);
11
12namespace chillerlan\Utilities;
13
14use function array_key_first;
15use function array_key_last;
16use function array_keys;
17use function count;
18use function random_int;
19use const PHP_VERSION_ID;
20
21/**
22 * Array functions
23 */
24final class Arr{
25
26 /**
27 * Returns the first element of an array, `null` if the given array is empty.
28 *
29 * @param array<string|int, mixed> $array
30 *
31 * @codeCoverageIgnore
32 */
33 public static function first(array $array):mixed{
34
35 if($array === []){
36 return null;
37 }
38
39 return $array[array_key_first($array)];
40 }
41
42 /**
43 * Returns the last element of an array, `null` if the given array is empty.
44 *
45 * @param array<string|int, mixed> $array
46 *
47 * @codeCoverageIgnore
48 */
49 public static function last(array $array):mixed{
50
51 if($array === []){
52 return null;
53 }
54
55 return $array[array_key_last($array)];
56 }
57
58 /**
59 * Returns a random element of the given array, `null` if the given array is empty.
60 *
61 * @see \random_int() - PHP <= 8.1
62 * @see \Random\Randomizer::pickArrayKeys() - PHP >= 8.2
63 *
64 * @param array<string|int, mixed> $array
65 *
66 * @noinspection PhpFullyQualifiedNameUsageInspection
67 */
68 public static function random(array $array):mixed{
69
70 if($array === []){
71 return null;
72 }
73
74 if(PHP_VERSION_ID >= 80200){
75 $key = (new \Random\Randomizer(new \Random\Engine\Secure))->pickArrayKeys($array, 1)[0];
76 }
77 else{
78 // array_rand() is not cryptographically secure
79 $keys = array_keys($array);
80 $key = $keys[random_int(0, (count($keys) - 1))];
81 }
82
83 return $array[$key];
84 }
85
86}