开发者

Generating numbers and randomly displaying them

开发者 https://www.devze.com 2023-01-18 15:31 出处:网络
I want generate a list of numbers from 0000 to 9999. I would then like to take all the results 开发者_开发技巧and echo them out randomly. (not in order) How would I do this?

I want generate a list of numbers from 0000 to 9999. I would then like to take all the results 开发者_开发技巧and echo them out randomly. (not in order) How would I do this?

Thank you in advance!


$numbers = range(0,9999);
shuffle($numbers);
foreach($numbers as $number) {
   echo str_pad($number,4,'0',STR_PAD_LEFT),'<br />';
}


To generate a list of 0000 to 9999, you can do something like this:

<?php

$array_list = array();
$end  =9999;
for($idx=0; $idx<=$end; $idx++)
{
    $array_list[$idx] = str_pad($idx, 4, 0, STR_PAD_LEFT);
}
?>

To generate that list randomly, you can use array_rand():

<?php
for($idx=0; $idx<=9; $idx++)
{
    echo array_rand( $array_list );
}
?>


Edit:

Here..

$randarr = array();
for ($i = 0; $i < 9999; $i++) {
    array_push($randarr, $i);
}

shuffle($randarr);

foreach($randarr as $randval) {
    echo $randval . "\n";
}


PHP does have some basic functions to generate this range:

$aRange = range(0, 9999);
shuffle($aRange);
print_r($aRange);

print the 4 digits output:

foreach($aRange as $number) {
    print str_pad($number, 4, 0, STR_PAD_LEFT);
}


Check out PHP's rand() function.

You could do something like:

for ( $counter=0; $counter < 10000; $counter += 1) { 
    $rand=rand(0,9999); echo $rand."<br />";
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消