How to use the Array_rand function in PHP

Source: Internet
Author: User


From an array of random out of n values, with Array_rand () can be easily implemented, when facing a large array, we will worry about his efficiency, performance problems.

I tested it, and when it was randomly taken out of 20 values in an array of size 10,000, that is, Array_rand ($arr, 20), the program only cost about 0.005s, and the efficiency was very high. Usually do not encounter such a large array bar, so we do not have to worry about array_rand efficiency problems.

At the same time, I used a different method of random numbers.

$arr = Array (1,2,3,4,5...9999);
For ($i =0 $i <20; $i + +)
{
$rands = Mt_rand (0,9999);
$AA [] = $arr [$rands];
}

It only takes about 0.005s to run the program.

instances, random arrays

function Make_password ($length = 8)
{
Password character set, you can add any character you need
$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 ', ' 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 ',
' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', '! ',
' @ ', ' # ', ' $ ', '% ', ' ^ ', ' & ', ' * ', ' (', ') ', '-', ' _ ',
' [', '] ', ' {', '} ', ' < ', ' > ', ' ~ ', ' ', ' + ', ' = ', ', ', ', ', ', ', '
'.', ';', ':', '/', '?', '|');

Randomly taking $length array element key name in a $chars
$keys = Array_rand ($chars, $length);

$password = ';
for ($i = 0; $i < $length; $i + +)
{
To concatenate $length array elements into strings
$password. = $chars [$keys [$i]];
}

return $password;
}

I suspect that the Array_rand algorithm might be the way it was done. So take the random value in the array, rest assured bold use Array_rand bar.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.