Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

How to shuffle an array (randomize the order of the elements in an array) in PHP

4 Answers

0 votes
$arr = array("aaa", "bbb", "ccc", "ddd", "eee", "fff");
print_r($arr); 
echo "<br />";
shuffle($arr);
print_r($arr); 


/*
run:

Array ( [0] => aaa [1] => bbb [2] => ccc [3] => ddd [4] => eee [5] => fff )
Array ( [0] => eee [1] => bbb [2] => ccc [3] => aaa [4] => fff [5] => ddd ) 
   
*/


answered Jul 4, 2014 by avibootz
edited Mar 9, 2016 by avibootz
0 votes
$arr = array("a"=>"aaa", "b"=>"bbb", "c"=>"ccc", "d"=>"ddd", "e"=>"eee");
print_r($arr); 
echo "<br />";
shuffle($arr);
print_r($arr); 


/*
run:

Array ( [a] => aaa [b] => bbb [c] => ccc [d] => ddd [e] => eee )
Array ( [0] => aaa [1] => ccc [2] => eee [3] => bbb [4] => ddd ) 
   
*/

 



answered Mar 9, 2016 by avibootz
0 votes
$arr = array(1, 2, 3 ,4, 5, 6, 7);
print_r($arr); 
echo "<br />";
shuffle($arr);
print_r($arr); 


/*
run:

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 )
Array ( [0] => 2 [1] => 7 [2] => 1 [3] => 4 [4] => 5 [5] => 6 [6] => 3 ) 
   
*/

 



answered Mar 9, 2016 by avibootz
0 votes
$arr = range(1, 10);

print_r($arr); 

echo "\n";

shuffle($arr);

print_r($arr); 


 
/*
run:
     
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
)

Array
(
    [0] => 1
    [1] => 10
    [2] => 7
    [3] => 5
    [4] => 4
    [5] => 9
    [6] => 2
    [7] => 8
    [8] => 3
    [9] => 6
)

*/

 



answered Jul 18, 2016 by avibootz
edited Feb 5, 2025 by avibootz

Related questions

1 answer 102 views
2 answers 445 views
1 answer 117 views
117 views asked Sep 30, 2021 by avibootz
1 answer 140 views
140 views asked Mar 2, 2019 by avibootz
2 answers 151 views
151 views asked Mar 28, 2021 by avibootz
1 answer 172 views
...