diff --git a/src/Faker/Provider/Base.php b/src/Faker/Provider/Base.php index f1650cb216..6ec881837a 100644 --- a/src/Faker/Provider/Base.php +++ b/src/Faker/Provider/Base.php @@ -161,18 +161,19 @@ public static function randomAscii() /** * Returns randomly ordered subsequence of $count elements from a provided array * - * @param array $array Array to take elements from. Defaults to a-f - * @param integer $count Number of elements to take. + * @param array $array Array to take elements from. Defaults to a-f + * @param integer $count Number of elements to take. + * @param boolean $allowDuplicates Allow elements to be picked several times. Defaults to false * @throws \LengthException When requesting more elements than provided * * @return array New array with $count elements from $array */ - public static function randomElements(array $array = array('a', 'b', 'c'), $count = 1) + public static function randomElements(array $array = array('a', 'b', 'c'), $count = 1, $allowDuplicates = false) { $allKeys = array_keys($array); $numKeys = count($allKeys); - if ($numKeys < $count) { + if (!$allowDuplicates && $numKeys < $count) { throw new \LengthException(sprintf('Cannot get %d elements, only %d in array', $count, $numKeys)); } @@ -182,11 +183,14 @@ public static function randomElements(array $array = array('a', 'b', 'c'), $coun while ($numElements < $count) { $num = mt_rand(0, $highKey); - if (isset($keys[$num])) { - continue; + + if (!$allowDuplicates) { + if (isset($keys[$num])) { + continue; + } + $keys[$num] = true; } - $keys[$num] = true; $elements[] = $array[$allKeys[$num]]; $numElements++; } diff --git a/test/Faker/Provider/BaseTest.php b/test/Faker/Provider/BaseTest.php index 6fc0cc90c2..313b0021c4 100644 --- a/test/Faker/Provider/BaseTest.php +++ b/test/Faker/Provider/BaseTest.php @@ -547,5 +547,9 @@ public function testRandomElements() $this->assertContains('foo', $shuffled); $this->assertContains('bar', $shuffled); $this->assertContains('baz', $shuffled); + + $allowDuplicates = BaseProvider::randomElements(array('foo', 'bar'), 3, true); + $this->assertCount(3, $allowDuplicates); + $this->assertContainsOnly('string', $allowDuplicates); } }