shuffle() randomizes an array in place and reindexes numeric keys. It returns true rather than a shuffled copy, so inspect the same array after calling it.
$items = ['A', 'B', 'C', 'D'];
shuffle($items);
print_r($items);Use shuffle() for ordinary random ordering, not for security-sensitive randomness.
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.
$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
$my_array=array('One','Two','Three','Four','Five');
shuffle($my_array);
echo "<br><br>";
foreach ($my_array as $key => $val) {
echo "$key -> $val <br>";
}
Output0 -> Two
1 -> Five
2 -> Three
3 -> Four
4 -> One
$my_array=array('Fruits1' =>'Banana','Fruits2'=>'Mango','Fruits3'=>'Apple','Fruits4'=>'Grapes');
shuffle($my_array);
foreach ($my_array as $key => $val) {
echo "$key -> $val <br>";
}
Output 0 -> Mango
1 -> Apple
2 -> Banana
3 -> Grapes
$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++) {
foreach ($my_array[$i] as $key => $val) {
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
$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. Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.