Skip to content

[5.4] Add $num optional parameter to Arr::random() #19818

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 29, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions src/Illuminate/Support/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -441,12 +441,25 @@ public static function pull(&$array, $key, $default = null)
/**
* Get a random value from an array.
*
* @param array $array
* @param array $array
* @param int $num
* @return mixed
*/
public static function random($array)
public static function random($array, $num = 1)
{
return $array[array_rand($array)];
if ($num == 1) {
return $array[array_rand($array)];
}

$keys = array_rand($array, $num);

$results = [];

foreach ($keys as $key) {
$results[] = $array[$key];
}

return $results;
}

/**
Expand Down
7 changes: 4 additions & 3 deletions src/Illuminate/Support/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -249,12 +249,13 @@ function array_pull(&$array, $key, $default = null)
/**
* Get a random value from an array.
*
* @param array $array
* @param array $array
* @param int $num
* @return mixed
*/
function array_random($array)
function array_random($array, $num = 1)
{
return Arr::random($array);
return Arr::random($array, $num);
}
}

Expand Down
8 changes: 7 additions & 1 deletion tests/Support/SupportArrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -403,8 +403,14 @@ public function testRandom()
{
$randomValue = Arr::random(['foo', 'bar', 'baz']);

$this->assertInternalType('string', $randomValue);
$this->assertContains($randomValue, ['foo', 'bar', 'baz']);

$randomValues = Arr::random(['foo', 'bar', 'baz'], 2);

$this->assertInternalType('array', $randomValues);
$this->assertCount(2, $randomValues);
$this->assertContains($randomValues[0], ['foo', 'bar', 'baz']);
$this->assertContains($randomValues[1], ['foo', 'bar', 'baz']);
}

public function testSet()
Expand Down