Skip to content

Commit 8ee941d

Browse files
authored
Add the function
1 parent 4df3a37 commit 8ee941d

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

iterable_to_array.func.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
3+
/**
4+
* Copyright (C) 2021 Navarr T. Barnier. All rights reserved.
5+
* Licensed under MIT License.
6+
*/
7+
8+
namespace Navarr\Utils;
9+
10+
use JetBrains\PhpStorm\Pure;
11+
12+
use function is_array;
13+
use function iterator_to_array;
14+
15+
/**
16+
* Converts any iterable into an array
17+
*
18+
* Designed to reduce boilerplate of testing if an iterable is an array before calling {@see iterator_to_array}
19+
*
20+
* @param iterable $iterable <p>
21+
* The iterator being copied.
22+
* </p>
23+
* @param bool $preserve_keys [optional] <p>
24+
* Whether to use the iterator element keys as index.
25+
* </p>
26+
* @return array An array containing the elements of the iterable.
27+
*/
28+
#[Pure]
29+
function iterable_to_array(iterable $iterable, bool $preserve_keys = true): array
30+
{
31+
return is_array($iterable) ? $iterable : iterator_to_array($iterable, $preserve_keys);
32+
}

0 commit comments

Comments
 (0)