Welcome to the Treehouse Community
Looking to learn something new?
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,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
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.