Random error

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
uberpolak
Forum Contributor
Posts: 261
Joined: Thu Jan 02, 2003 10:37 am
Location: Next to the bar

Random error

Post by uberpolak »

Using this function:

Code: Select all

<?php
function randstring($zork)
{
 $chars = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
 $stringsofar = "";
 srand((double)microtime()*1000000);
 for ($z = 1; $z <= $zork; $z++)
 {
  $stringsofar .= $chars[rand(0,sizeof($chars) - 1)];
 }
 return $stringsofar;
}

?>
I keep getting returned a value of "a a a a a a a a ", not random, and with spaces... this makes no sense to me, can anyeone tell me what's wrong with it?
glo-wurm
Forum Newbie
Posts: 13
Joined: Mon Jan 13, 2003 2:07 pm
Location: Naples, FL

Post by glo-wurm »

works fine for me
User avatar
mydimension
Moderator
Posts: 531
Joined: Tue Apr 23, 2002 6:00 pm
Location: Lowell, MA USA
Contact:

Post by mydimension »

found a different random string generator on php.net:

Code: Select all

//
// Generates a random string with the specified length
// Chars are chosen from the provided &#1111;optional] list
//
function simpleRandString($length=16, $list="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") &#123;
  mt_srand((double)microtime()*1000000);
  $newstring="";

  if($length>0)&#123;
    while(strlen($newstring)<$length)&#123;
      $newstring.=$list&#1111;mt_rand(0, strlen($list)-1)];
    &#125;
  &#125;
  return $newstring;
&#125;
found in one of the user comments here: http://www.php.net/manual/en/function.mt-rand.php

i like that it dosen't use an array to store the character list and it has a default list to use.
Post Reply