I want to create a random number in PHP where numbers should not be repeated in that number. Is it possible? Can you insert sample code here? Example: 674930, 145289. [The same number should not arrive] Thank you
Here is a good way to do this:
$amountOfDigits = 6; $numbers = range(0,9); shuffle($numbers); for($i = 0;$i < $amountOfDigits;$i++) $digits .= $numbers[$i]; echo $digits; //prints 217356
If you want a neat function, you can create something like this:
function randomDigits($length){ $numbers = range(0,9); shuffle($numbers); for($i = 0;$i < $length;$i++) $digits .= $numbers[$i]; return $digits; }
function randomize($len = false) { $ints = array(); $len = $len ? $len : rand(2,9); if($len > 9) { trigger_error('Maximum length should not exceed 9'); return 0; } while(true) { $current = rand(0,9); if(!in_array($current,$ints)) { $ints[] = $current; } if(count($ints) == $len) { return implode($ints); } } } echo randomize(); //Numbers that are all unique with a random length. echo randomize(7); //Numbers that are all unique with a length of 7
Something along these lines should do it
<?php function genRandomString() { $length = 10; // set length of string $characters = '0123456789'; // for undefined string $string =""; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } return $string; } $s = genRandomString(); //this is your random print var or function rand_string( $length ) { $chars = "0123456789"; $size = strlen( $chars ); for( $i = 0; $i < $length; $i++ ) { $str .= $chars[ rand( 0, $size – 1 ) ]; } return $str; } $rid= rand_string( 6 ); // 6 means length of generate string ?>
$result= ""; $numbers= "0123456789"; $length = 8; $i = 0; while ($i < $length) { $char = substr($numbers, mt_rand(0, strlen($numbers)-1), 1); //prevents duplicates if (!strstr($result, $char)) { $result .= $char; $i++; } }
. $numbers char, , : , ..
, - , :
function random_num($n=5) { return rand(0, pow(10, $n)); }
But I assume that this requires more processing than these other methods.
Source: https://habr.com/ru/post/1752265/More articles:Is padding between members of a class of the same type the same? - c ++Killing a process on Linux - linuxDetermine in IE8 compatibility mode using conditional expressions - internet-explorer-8Running multiple cURL queries - phpHow to use maven-jboss plugin? If I want to start a war, how to do it? - javaКак определить URL-адрес веб-приложения Java изнутри? - javaIE6: Large file downloads fail and the page cannot be displayed? - internet-explorerXAML image source is set dynamically based on content - pathCode Insight (IntelliSense) - delphiunicode preg_replace problem in php - phpAll Articles