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.
Mike CostaCourses 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
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.