1

I have a list of non-repetitive numbers; i need to display all these numbers in a random manner. From http://www.w3schools.com/php/func_array_rand.asp I learn a few approaches without luck. If i use "array_rand" all the outputs must be in an increasing order; so my final output will always be in sequential order from 1 to 10 with no randomness.

<!DOCTYPE html> <html> <body> <?php $a=array(1,2,3,4,5,6,7,8,9,10); $random_keys=array_rand($a,10); echo $a[$random_keys[0]]."<br>"; echo $a[$random_keys[1]]."<br>"; echo $a[$random_keys[2]]."<br>"; echo $a[$random_keys[3]]."<br>"; echo $a[$random_keys[4]]."<br>"; echo $a[$random_keys[5]]."<br>"; echo $a[$random_keys[6]]."<br>"; echo $a[$random_keys[7]]."<br>"; echo $a[$random_keys[8]]."<br>"; echo $a[$random_keys[9]]."<br>"; ?> </body> </html> 
2
  • 2
    What do you mean by "if I use array_rand all the outputs must be in an increasing order"? Can you clarify? Commented Apr 15, 2016 at 15:03
  • 1
    1st tip - don't use w3schools use more reputable sources like the PHP manual (php.net/manual/en/function.array-rand.php). 2nd tip - use a foreach loop to print out your array Commented Apr 15, 2016 at 15:03

5 Answers 5

6

The shuffle function will randomize the order of the elements in the array for you.

$a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; shuffle($a); echo implode('<br>', $a); 
Sign up to request clarification or add additional context in comments.

Comments

2

The PHP you're actually looking for is:

$a = array(1,2,3,4,5,6,7,8,9,10); shuffle($a); foreach($a as $n){ echo "$n<br>"; } 

array_rand

Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.

shuffle

shuffles (randomizes the order of the elements in) an array

Comments

1

use php array shuffle

<!DOCTYPE html> <html> <body> <?php $a=array(1,2,3,4,5,6,7,8,9,10); print_r($a); shuffle($a); echo "<br/>"; print_r($a); ?> </body> </html> 

Comments

1

Use the function shuffle to randomize the elements of the array:

$a=array(1,2,3,4,5,6,7,8,9,10); shuffle($a); 

Info: http://php.net/manual/es/function.shuffle.php

Comments

1
<!DOCTYPE html> <html> <body> <?php $numbers = range(1, 10); shuffle($numbers); foreach ($numbers as $number) { echo "$number<br>"; } ?> </body> </html> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.