Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

Random array display.

Hello,

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
PLUS
Mike Costa
Courses Plus Student 26,361 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
STAFF
Ken Alger
Treehouse Teacher

Kristian;

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,

Ken

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.