HELP NEEDED - Display text in random order

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
mit123
Forum Newbie
Posts: 3
Joined: Sat Jul 30, 2005 10:38 am

HELP NEEDED - Display text in random order

Post by mit123 »

I was hoping some one on this forum would be able to help me with my problem. I am relatively new to PHP and therefore do not know a great deal.

What I am trying to achieve is get PHP to display an XML file. I have managed to get that working. However, I would like to have the text displayed in random order.

Example:

<answer><?php echo $name_row[1]</answer>
<answer><?php echo $name_row[2]</answer>
<answer><?php echo $name_row[3]</answer>

The code processed would display

<answer>Windows</answer>
<answer>Linux</answer>
<answer>Unix</answer>

But I would like it to display in a random order each time the php page is processed, rather than in the same order ie. Linux, Unix, Windows or Windows, Unix, Linux etc.

Any help from members on this forum would be greatly appreciated.

Cheers
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post by nielsene »

Look at the shuffle() function. Note that it will rearrange the rows of the orginial array. If you need to keep a copy in the orginal order, make a copy first.
theda
Forum Contributor
Posts: 332
Joined: Sat Feb 19, 2005 8:35 am
Location: USA

Post by theda »

An idea:

Have something create a random integer between 1 and 3..., but have 1, 2, 3 defined as Windows, etc... And for the second one <> if the first one is equal to 1, 2, 3, exclude whichever was up there, and random between the last two integers, and then the third one would equal whatever else wasn't chosen. What this equals in PHP, I haven't a clue, but could be a good option.

Example:

Spot 1 choses between 1-3. If it equals 2 then:
Spot 2 choses either 1 or 3.
Spot 3 choses the last remaining...
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

nielsene's idea is probebly the best but if you are going to use the other idea then just use rand(0, 4); to get the random number but using shuffle will be able a gillian times easier
mit123
Forum Newbie
Posts: 3
Joined: Sat Jul 30, 2005 10:38 am

Post by mit123 »

Thanks for your help guys. Much appreciated.
Post Reply