Skip to content

Commit d58c775

Browse files
authored
Merge pull request #2 from simPod/use_keys
Add `use_keys` for `iterable_to_array()`
2 parents 0cc66fe + f19678b commit d58c775

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

src/iterable-functions.php

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,13 @@ function is_iterable($iterable)
2727
/**
2828
* Copy the iterable into an array. If the iterable is already an array, return it.
2929
*
30-
* @param array|\Traversable $iterable
30+
* @param iterable $iterable
31+
* @param bool $use_keys [optional] Whether to use the iterator element keys as index.
3132
* @return array
3233
*/
33-
function iterable_to_array($iterable)
34+
function iterable_to_array($iterable, $use_keys = true)
3435
{
35-
return is_array($iterable) ? $iterable : iterator_to_array($iterable);
36+
return is_array($iterable) ? ($use_keys ? $iterable : array_values($iterable)) : iterator_to_array($iterable, $use_keys);
3637
}
3738
}
3839

tests/TestIterableToArray.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,24 @@ public function testIteratorToArray()
1616
$this->assertEquals(array('foo', 'bar'), iterable_to_array($iterator));
1717
}
1818

19+
public function testIteratorWithoutKeysToArray()
20+
{
21+
$iterator = new ArrayIterator(array(1 => 'foo', 2 => 'bar'));
22+
$this->assertEquals(array(0 => 'foo', 1 => 'bar'), iterable_to_array($iterator, false));
23+
}
24+
1925
public function testArrayToArray()
2026
{
2127
$array = array('foo', 'bar');
2228
$this->assertEquals(array('foo', 'bar'), iterable_to_array($array));
2329
}
2430

31+
public function testArrayWithoutKeysToArray()
32+
{
33+
$array = array(1 => 'foo', 2 => 'bar');
34+
$this->assertEquals(array(0 => 'foo', 1 => 'bar'), iterable_to_array($array, false));
35+
}
36+
2537
public function testScalarToArray()
2638
{
2739
$scalar = 'foobar';

0 commit comments

Comments
 (0)