Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Random array display.


I was thinking over a school project(system for web exams) I wont go into details unless someone asks me. So I wanted to add an extra layer of security by randomizing the answers for a question. I use php for the back-end and I store the questions and answers into a MySQL database.

When I take the elements from the database I store them in array so for question 1 there is an array with four elements (four answers) and this is the array I want to randomize.

So if the array looks like this array(1, 2, 3, 4); and I do a foreach loop to echo each element I will get this: 1 2 3 4 but I want something more like: 2 4 3 1 or 4 2 1 3. I think you get the point.

Hi Kristian,

I would suggest the shuffle function too but I think the solution is going to depend on how you're storing the correct answer. You didn't give any information about that. This looks like some kind of multiple choice questions where you have 4 choices.

How are you storing what the correct answer is?

3 Answers

Mike Costa
Mike Costa
Courses Plus Student 26,362 Points

I would use the shuffle function. shuffle function takes an array and shuffles the values of the array while keeping the keys in tact. so if you have

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

shuffle will turn that array into

$array = array(3,1,4,2); // or whatever random combo shuffle chooses
Ken Alger
Ken Alger
Treehouse Teacher


I would take a look at the PHP array_rand function which allows one to pick one or more random entries out of an array. You can read more about it in the PHP Manual which also gives some examples and alternatives.

Happy coding,


Thank you all for the answers and sorry for the late reply from my side but i wanted to test how it works with my project. I ended up using shuffle function as Mike and Jason suggested. Thank you all again you really helped me.