rockinaway Posted May 31, 2011 Share Posted May 31, 2011 I want to loop through all the values of an array.. but each time, JUST FOR THE LOOP, i want to go through the array values randomly. How do you suggest I do this? Link to comment https://forums.phpfreaks.com/topic/238037-foreach-but-random/ Share on other sites More sharing options...
Pikachu2000 Posted May 31, 2011 Share Posted May 31, 2011 How about making a copy of the array and shuffle() it, then use that in the foreach() loop? $new_array = $old_array; shuffle($new_array); foreach( $new_array as $k => $v) { // etc . . . Link to comment https://forums.phpfreaks.com/topic/238037-foreach-but-random/#findComment-1223223 Share on other sites More sharing options...
fugix Posted May 31, 2011 Share Posted May 31, 2011 Do you want to loop through them randomly or simply echo them randomly. Perhaps if I more clearly understood what you are trying to do Link to comment https://forums.phpfreaks.com/topic/238037-foreach-but-random/#findComment-1223224 Share on other sites More sharing options...
rockinaway Posted June 1, 2011 Author Share Posted June 1, 2011 I was thinking the same as Pikachu2000. Basically, if I have $array1. And it has 5 values. I want to loop through these values in a RANDOM order but retain their order in $array1. So as Pikachu2000 stated, making a copy of the array to say $array2, shuffling it and then looping through it (not necessarily echoing anything) would work as then I can return to $array1 with everything preserved in the correct order. I just want to know if there is a simpler way.. Link to comment https://forums.phpfreaks.com/topic/238037-foreach-but-random/#findComment-1223384 Share on other sites More sharing options...
revraz Posted June 1, 2011 Share Posted June 1, 2011 Simpler? Looks pretty simple as is, how much simpler do you want it? Link to comment https://forums.phpfreaks.com/topic/238037-foreach-but-random/#findComment-1223389 Share on other sites More sharing options...
fugix Posted June 1, 2011 Share Posted June 1, 2011 I was thinking the same as Pikachu2000. Basically, if I have $array1. And it has 5 values. I want to loop through these values in a RANDOM order but retain their order in $array1. So as Pikachu2000 stated, making a copy of the array to say $array2, shuffling it and then looping through it (not necessarily echoing anything) would work as then I can return to $array1 with everything preserved in the correct order. I just want to know if there is a simpler way.. there are other ways to do it, but as far as simplicity is concerned, the example that Pikachu2000 provided is what you want Link to comment https://forums.phpfreaks.com/topic/238037-foreach-but-random/#findComment-1223466 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.