Forum : How can I mix up the order of values in an array?
Brief description  about Online courses   join in Online courses
View Sheetal  Panday 's Profile

How can I mix up the order of values in an array?

Sir,

How can I mix up the order of values in an array?
Asked by Sheetal Panday | Nov 27, 2009 |  Reply now
Replies (2)
View manju s-reddy 's Profile
Hi..
We can use shuffle() function to randomizes the order of the elements & values in the array.

This function assigns new keys for the elements in the array. Existing keys will be removed.

This function returns TRUE on success, or FALSE on failure.

Example:

<?php
$my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");

shuffle($my_array);
print_r($my_array);
?>

output: Array ( [0] => Cat [1] => Horse [2] => Dog )
Feb 17, 2010
View teacher siliconindia 's Profile
hi sheetal panday,

A simple way to achieve the result of mixing up the values in an array is to use the shuffle function, which takes the name of the array you want to randomise. Here is a code snippet to demonstrate the shuffle function in action:

<?php
$values = range("A","Z");
shuffle($values);
print_r($values);
?>

This will print something like the below, shuffling up the letters of the alphabet:

Array
(
[0] => J
[1] => R
[2] => C
[3] => W
[4] => Y
[5] => L
[6] => B
[7] => A
[8] => P
[9] => O
[10] => M
[11] => V
[12] => D
[13] => X
[14] => F
[15] => S
[16] => Q
[17] => G
[18] => I
[19] => H
[20] => N
[21] => Z
[22] => U
[23] => E
[24] => K
[25] => T
)
Nov 27, 2009