My Tutorial

It's Our e-Learning database…

php-logo

Generate a random order number in PHP

| 1 Comment

Here is a simple code to generate a random order number in PHP. In my case, I want to display number item 1, 2, 3, 4, 5 but in random order like:

13452

53241

23514 etc

<?php
$number = array( 1,2,3,4,5 );
for ( $i = 0; $i < 5; $i++ ){
 shuffle( $number );
 echo $number&#91;0&#93;;
 unset( $number&#91;0&#93; );
}
?>

For the real world example, hmmm maybe a simple quiz application. The code goes like this:

<?php
echo "Quiz question? <br />";
$number = array( 1,2,3,4,5 );
$ask = array(
 "1" => "answer no 1",
 "2" => "answer no 2",
 "3" => "answer no 3",
 "4" => "answer no 4",
 "5" => "answer no 5"
 );
for ( $i = 0; $i < 5; $i++ ){
 shuffle( $number );
 echo "<input type='radio' name='radio' value='".$number&#91;0&#93;."' /> ".$ask[$number[0]]."<br />";
 unset( $number[0] );
}
?>

Taken from my post at TudaBit.com, Hope it’s useful

Author: DiCK DuMBSTRaCK

Founder of DuMBSTRaCK, like playing music, drawing and writing. Love to see this nature become a better place :)