note 86826 modified in function.rand by danbrown

From: Date: Wed, 05 Nov 2008 15:33:53 +0000
Subject: note 86826 modified in function.rand by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-146165@lists.php.net to get a copy of this message
This is a function to generate numbers of any length which contain no identical characters side-by-side. i.e. 11aa22bb33 <?php function createRandom($number_of_digits=1,$type=3){ // type: 1 - numeric, 2 - letters, 3 - mixed. for($x=0;$x<$number_of_digits;$x++){ while(substr($num,strlen($num)-1,strlen($num)) == $r){ switch($type){ case "1": $r = rand(0,9); break; case "2": $r = chr(rand(0,25)+65); break; case "3": if(is_numeric(substr($num,strlen($num)-1,strlen($num)))){ $n = rand(0,999); if($n % 2){ $r = chr(rand(0,25)+65); } else { $r = strtolower(chr(rand(0,25)+65)); } } else { $r = rand(0,9); } break; } } $new_string .= $r; } return $new_string; } // Usage Examples Below - // $number = createRandom(10); // echo $number; // Output: 6Q1a8C1u9S // echo createRandom(10,1); // Output: 8754381046 // echo createRandom(10,2); // Output: dNAoQYOtud // echo createRandom(); // Output: 9 ?> --was-- *** Moderator *** please replace or delete my comment from Oct 10 as there is an error in the function I posted. Below is the corrected version. Thanks!!! *** This is a function to generate numbers of any length which contain no identical characters side-by-side. i.e. 11aa22bb33 <?php function createRandom($number_of_digits=1,$type=3){ // type: 1 - numeric, 2 - letters, 3 - mixed. for($x=0;$x<$number_of_digits;$x++){ while(substr($num,strlen($num)-1,strlen($num)) == $r){ switch($type){ case "1": $r = rand(0,9); break; case "2": $r = chr(rand(0,25)+65); break; case "3": if(is_numeric(substr($num,strlen($num)-1,strlen($num)))){ $n = rand(0,999); if($n % 2){ $r = chr(rand(0,25)+65); } else { $r = strtolower(chr(rand(0,25)+65)); } } else { $r = rand(0,9); } break; } } $new_string .= $r; } return $new_string; } // Usage Examples Below - // $number = createRandom(10); // echo $number; // Output: 6Q1a8C1u9S // echo createRandom(10,1); // Output: 8754381046 // echo createRandom(10,2); // Output: dNAoQYOtud // echo createRandom(); // Output: 9 ?> http://php.net/manual/en/function.rand.php

« previous php.notes (#146165) next »