Reply
random numbers in php
Old 07-29-2010, 03:19 AM random numbers in php
Average Talker

Posts: 18
Name: Philips Tel
Trades: 0
here is my simple code to random numbers from 0 - 5:

PHP Code:
for( $i 0$i <= 5$i++) {
     echo 
mt_rand(05). ", ";

after running it many times, i got brief result as follows:
1, 4, 4, 5, 0
4, 0, 1, 5, 0
3, 2, 1, 1, 3
..
& so on..

my question is, what is the script in order the result doesn't contain DUPLICATE numbers like above.

I like the result something like this:
1, 5, 0, 3, 2
4, 1, 2, 3, 0

...
philips is offline
Reply With Quote
View Public Profile
 
 
When You Register, These Ads Go Away!
Old 07-29-2010, 04:13 AM Re: random numbers in php
mtishetsky's Avatar
King Spam Talker

Posts: 1,224
Name: Mike
Location: Mataro, Spain
Trades: 0
PHP Code:
while (count($array) < 5) {
   
$ret mt_rand(05);
   if (!
in_array($ret$array))
      
$array[] = $ret;
}

print_r($array); 
__________________
Free Nokia Themes - 共享软件下载 - Mobile Themes for Nokia N95 8GB
And don't forget to give me talkupation!
mtishetsky is offline
Reply With Quote
View Public Profile Visit mtishetsky's homepage!
 
Old 07-29-2010, 12:41 PM Re: random numbers in php
Skilled Talker

Posts: 88
Name: John Dacu
Trades: 0
Indeed. All you have to do if you want unique values is to check every generated value with previews ones saved already in an array. If the value already exists then try it again.
johnny.dacu is offline
Reply With Quote
View Public Profile
 
Old 07-30-2010, 03:54 AM Re: random numbers in php
Average Talker

Posts: 18
Name: Philips Tel
Trades: 0
@johnny.dacu:
yeah, u're right

@mtishetsky :
i've modified a bit of your script and it works.

PHP Code:
$i 0;
$arrVar = array();
while( 
$i <= ) {
      
$rand_value mt_rand(05);
      if( !
in_array($rand_value$arrVar) ) {
          echo 
$rand_value;
      } else {
          continue;
      }
      
$arrVar[$i] = $rand_value;
      
$i++;
}

Thank You

Last edited by philips; 07-30-2010 at 03:56 AM.. Reason: script is uncomplete.
philips is offline
Reply With Quote
View Public Profile
 
Reply     « Reply to random numbers in php
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off





   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML

 


Page generated in 0.12031 seconds with 13 queries