shuffle?

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
jonathant
Forum Commoner
Posts: 32
Joined: Sat Jan 07, 2006 3:13 pm

shuffle?

Post by jonathant »

Is there a function that will take a numeric array and just randomize the items within it? I was trying to use shuffle() but it was returning a boolean, and not the rearranged array itself. PHP5 probably has a function that does this, but I'm not having any luck finding it.

Code: Select all

$my_array=(1, 2, 3, 4);

$new_array=randomize_function($my_array);

// now, $new_array should equal array(3, 1, 4, 2);
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: shuffle?

Post by Christopher »

jonathant wrote:I was trying to use shuffle() but it was returning a boolean, and not the rearranged array itself.
It shuffles the array you pass it.

Code: Select all

$my_array=(1, 2, 3, 4);
$new_array=$my_array;
shuffle($new_array);
(#10850)
jonathant
Forum Commoner
Posts: 32
Joined: Sat Jan 07, 2006 3:13 pm

Post by jonathant »

Here is what I'm trying to do. $hompage_list_array contains item ids in a numeric array.

Code: Select all

$list_shuffled=shuffle($homepage_list_array);  // shuffle the order, so the displayed items will be random
while (count($list_shuffled) <=   // only take the first 8 because that is all the homepage template can fit
{
	array_pop($list_shuffled);
}
return $list_shuffled;
But, I'm getting this error: Warning: array_pop() [function.array-pop]: The argument should be an array in C:\Program Files\xampp\htdocs\dev\hubuy\includes\datasearch.php5 on line 36
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Might help to take a look at the manual :wink:
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: shuffle?

Post by Christopher »

Code: Select all

$my_array=(1, 2, 3, 4, 6, 7, ;
$new_array=$my_array;
shuffle($new_array);
$newer_array = array_slice($new_array, 0, ;
(#10850)
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

don't store the shuffled array in a variable

Code: Select all

// this is correct

$array = array(1,2,3,4,5);
shuffle($array);
print_r($array);

// this is incorrect

$array = array(1,2,3,4,5);
$shuffled = shuffle($array);
print_r($shuffled);
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Post Reply