Home >Backend Development >PHP Tutorial >PHP random number code: Examples of PHP generating random numbers and random strings

PHP random number code: Examples of PHP generating random numbers and random strings

WBOY
WBOYOriginal
2016-07-25 08:51:22918browse
  1. /**
  2. * @param string $type
  3. * @param $length
  4. * @return string
  5. */
  6. function randomString($type="number,upper,lower",$length){
  7. $valid_type = array('number','upper','lower');
  8. $case = explode(",",$type);
  9. $count = count($case);
  10. //根据交集判断参数是否合法
  11. if($count !== count(array_intersect($case,$valid_type))){
  12. return false;
  13. }
  14. $lower = "abcdefghijklmnopqrstuvwxyz";
  15. $upper = strtoupper($lower);
  16. $number = "0123456789";
  17. $str_list = "";
  18. for($i=0;$i<$count;++$i){
  19. $str_list .= $$case[$i];
  20. }
  21. return substr(str_shuffle($str_list),0,$length);
  22. }
  23. echo randomString("number,upper,lower",12);
复制代码


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn