Array Rand

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
$var
Forum Contributor
Posts: 317
Joined: Thu Aug 18, 2005 8:30 pm
Location: Toronto

Array Rand

Post by $var »

http://ca.php.net/array_rand

When using array_rand, I am getting no values at all.

The array ($story) returns an array of 7 elements, when not passed through array_rand
I want to get 4 of the 7 elements randomly.

$story = function($getThese, 7)
$story = array_rand($story ,4);

When using array_rand, my var_dump shows this:
array(4) { [0]=> int(1) [1]=> int(4) [2]=> int(2) [3]=> int(3) }

I am using a multi-dimensional array.
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Array Rand

Post by Mark Baker »

$var wrote:http://ca.php.net/array_rand

When using array_rand, I am getting no values at all.

$story = function($getThese, 7)
$story = array_rand($story ,4);
Yes you are, you're getting a set of keys exactly as the manual says you will.
But then you're overwriting the original array with this new array of keys.

Code: Select all

 
$storyKeys = array_rand($story ,4);
for each ($storyKeys as $storyKey) {
    print_r($story[$storyKey]);
}
 
Post Reply