Fixed Length & Large Random Numbers with PHP

Web-hosting business can now be started for just $19.95 with unlimited resources. Start your own.

PHP's random number functions generate integers with variable number of digits. Also, the maximum size of the random number generated that way is
PHP_INT_MAX
. You can remove these two limitations using the function below.



  1. //Returns string of specified length containing decimal characters
  2.  
  3. function big_rand( $len = 9 ) {
  4.     $rand   = '';
  5.     while( !( isset( $rand[$len-1] ) ) ) {
  6.         $rand   .= mt_rand( );
  7.     }
  8.     return substr( $rand , 0 , $len );
  9. }
PHP Code

How to use

What is different in this function is that you have to specify a length, rather than a range, to generate the random number. Here is how to use it:
  1. $rand = big_rand( 60 );
  2.  
  3. echo strlen( $rand );
  4. //Output: 60
PHP Code



  1. High Performance Hosting is now $3.96 a month
  2. Faster Random Numbers with PHP
  3. How to validate ASCII Text - PHP
  4. Implementing QuickSort in PHP
  5. register_globals is Back - PHP Implementation
  6. Remove undesired characters with trim_all() - PHP


© 2012-2017 PageConfig.com - Scripts - Twitter