shuffle(): Randomize the order of the elements fo array

shuffle($input_array);
Returns true on success and false on failure. The order of the elements of $input_array is changed and new key is assigned to each elements.

Example

$my_array=array(0,1,2,3,4,5,6);
shuffle($my_array);
foreach ($my_array as $element) {
    echo $element . "  ";
}
Output is here
4 2 0 5 3 1 6

Example

$my_array=array('One','Two','Three','Four','Five');
shuffle($my_array);
echo "<br><br>";
while (list ($key, $val) = each ($my_array)) {
echo "$key -> $val <br>";
}
Output
0 -> Two 
1 -> Five 
2 -> Three 
3 -> Four 
4 -> One 

Example with Literal Keys

$my_array=array('Fruits1' =>'Banana','Fruits2'=>'Mango','Fruits3'=>'Apple','Fruits4'=>'Grapes');
shuffle($my_array);
while (list ($key, $val) = each ($my_array)) {
echo "$key -> $val <br>";
}
Output
0 -> Mango 
1 -> Apple 
2 -> Banana 
3 -> Grapes 

Example with Multidimensional Aarray

$my_array=array(array("path"=>"php_tutorial","section"=>"php"),
array("path"=>"sql_tutorial","section"=>"sql"),
array("path"=>"javascript_tutorial","section"=>"js"),
array("path"=>"html_tutorial","section"=>"html"),
);
shuffle($my_array);
$max=sizeof($my_array);
for($i=0; $i<$max; $i++) { 

while (list ($key, $val) = each ($my_array[$i])) { 
echo "$key -> $val <br>"; 
} // inner array while loop

} // outer array for loop
Output is here
path -> javascript_tutorial 
section -> js 
path -> sql_tutorial 
section -> sql 
path -> php_tutorial 
section -> php 
path -> html_tutorial 
section -> html

Using range with shuffle

Creating an array with elements from 0 to 10 in random order.
$my_array=range(0,10);
shuffle($my_array);
foreach ($my_array as $element) {
    echo $element . "  ";
}
Output is here
4 5 2 3 7 9 1 8 10 0 6
All the above outputs will changed if you re run the script.


plus2net.com




Post your comments , suggestion , error , requirements etc here .




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer