array_rand() - 从数组中随机取出一个或多个单元 - php 数组函数
array_rand()
(PHP 4, PHP 5, PHP 7)
从数组中随机取出一个或多个单元
说明
array_rand(array $array[,int $num= 1]): mixed从数组中取出一个或多个随机的单元,并返回随机条目的一个或多个键。它使用了伪随机数产生算法,所以不适合密码学场景,
参数
$array输入的数组。
$num指明了你想取出多少个单元。
返回值
如果只取出一个,array_rand()返回随机单元的键名。否则就返回包含随机键名的数组。完成后,就可以根据随机的键获取数组的随机值。取出数量如果超过 array 的长度,就会导致E_WARNING
错误,并返回 NULL。
更新日志
版本 | 说明 |
---|---|
7.1.0 | 内置的随机数生成算法从 libc rand 函数改成»梅森旋转伪随机数生成算法。 |
5.2.10 | The resulting array of keys is no longer shuffled. |
范例
Example #1array_rand()例子
参见
shuffle()
打乱数组
Note: array_rand uses the libc generator, which is slower and less-random than Mersenne Twister. This is a better alternative.
If the array elements are unique, and are all integers or strings, here is a simple way to pick $n random *values* (not keys) from an array $array:
Looks like this function has a strange randomness. If you take any number of elements in an array which has 40..100 elements, the 31st one is always by far the less occuring (by about 10% less than others). I tried this piece of code at home (PHP Version 5.3.2-1ubuntu4.9) and on my server (PHP Version 5.2.17), unfortunately i haven't any server with the last version here : In every try, the number of occurrences change a bit but the 31 is always far less (around 2200) than the others (2400-2600). I tried with 50 and 100 elements, no change. I tried with more or less elements to pick (second parameter to array_rand), same result. If you pick only one element it's even worse : 31 has half the result of the others. For this particular case, i recommend shuffling the array and taking the nth first elements, in this test it's 60% faster and the statistics are ok.
An array of arrays example:
To select a random Value (not a Key) from a Multi-Dimentionnal array I made a recursive function : array_multi_rand() the following exemple randomly selects an url from a multidimentionnal array :
Random choice with a closure. $randomChoice = function($array) {return $array[array_rand($array)];}; $names = ['Dexter', 'Esther', 'David', 'Richard', 'Rachel', 'Belinda']; echo $randomChoice($names);
There was a mistake at "Paul Hodel (paul at ue dot com dot br) 17-Apr-2003 04:40": String echo $new_input = $input[$v]; have to be: echo $new_input[] = $input[$v];
Note that the int num_req parameter is the required number of element to randomly select. So if your array has 3 element and num_req=4 then array_rand() will not return anything since it is impossible to select 4 random elements out of an array that only contains 3 elements. Many people think that they will get 3 elements returned but that is of course not the case.
Modify of last note: mt_rand generates a better random number, and with the limit.
This is something I have been playing with for quite awhile. I'm very new to php, but i finally got it to work. it's a function that will take and array[$arrquo] and find a particular keyword[$find] in the different elements of the array then take those elements that posess that keyword and display them at random In my case I had this huge array of quotes with 90 some elements. I was able to find certain keywords in those elements then ONLY display the elements that had those keywords. NEAT! Maybe only because I'm new.
According to office at at universalmetropolis dot com I have to say that the example is wrong. The count() function will return the number of items in the array, that's the last index + 1. So if there's 2 items in the array, count() will return 2 but the indices are 0 and 1. Now since rand(x,y) randomizes between x and y inclusively the index from the above example may be out of bounds. Thus you have to subtract 1 from the count:
If you trying to get a randon array just use that... it's easier! And you have no repeats...
Well, this is interesting. I don't see anyone else commenting on this, so just in case you were planning to use this function like I was, be prepared: array_rand does not handle multidimensional arrays. It just ends up returning a list of the X-axis values without the Y-axis arrays. Bummer. I'm going to have to find another way to do what I wanted.
this is to generate a random selection from an array with array_rand preety nice, can be used to generate random passwords or anything: $my_array = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "0", "1", "2", "3", "4", "5"); for ($i=0; $i And yes, I know that my example returns a portion of the array and not just the key numbers
We can use this function to create random HEX Color codes : So each time we ran this script it will generate a random HEX color code and print it in the screen .
When the second argument is greater than 1, the output array will be arranged in ascending order. $a = ["Albert", "James", "Steve", "Charlie", "Sarah"]; The least value of array keys of $a is 0 and the highest is 4 in this case. Now let's do some tests. //Infinite loops (never ending loops) while(array_rand($a, 2)[0] !== 4); while(array_rand($a, 2)[1] !== 0); //Non-infinite loops. while(array_rand($a, 2)[0] === 0); while(array_rand($a, 2)[1] === 4); Why is this important? You will never get a perfectly random key if you aren't aware of that. array_rand($a, 2)[0] will NEVER return the last key (by the last key I mean the last key of the array when you arrange the array keys in ascending order). array_rand($a, 2)[1] will NEVER return the first key (by the first key I mean the first key of the array when you arrange the array keys in ascending order). In our case, $random = array_rand($a, 2); echo $a[$random[0]];//Possible output: "Albert", "James", "Steve" or "Charlie" echo $a[$random[1]];//Possible output: "James", "Steve", "Charlie" or "Sarah" You might want to shuffle($random) in such a case. This is only needed IF you have defined the second parameter and the second parameter > 1.
I'd recommend use random_int() instead of mt_rand()
It is not written on here but you should note that the keys that are returned are always sorted low to high. This was unexpected for me since my main reason to use this function was to get a random subset of an array (use case was to list products in a sidebar). As a result of this, even if the same products were picked randomly another time, they were always arranged in the same way. This is my solution, may help someone who also needs a fully randomized subset of an array:
Two things always bugged me with array_rand(). First is its name. It does not sound clear enough whether it gives key or values. Second and more importantly is its erratic randomness, which is already well documented. That is why I came up with these two simple functions: They both work well with any kind of arrays, do not alter the original one like shuffle, are giving more realistic random results, and their names are self describing. The main drawback is that, as opposed to array_rand, they only gives one element, but at least that is clear from their name. I do believe easy to make random_keys and random_values.
@Sebmil : You say this function "has a strange randomness [, because] the 31st one is always by far the less occuring (by about 10% less than others)." That's right (at least under linux, PHP 5.3). And it's also visible when calling array_rand with 1 as second parameter. After checking the code, and testing it, I concluded that you have to call srand() at each iteration of your loop. To be simple, a rand() call is made times when the th key is returned; I suppose there is a flaw in the pseudorandom number generator (PRNG) that php uses; somehow the generation has a frequency of 31 (when a random number is sufficiently low, then the 31st after it will be more higher). Reinitializing the PRNG each time you enter the loop make the problem disappear (and is cheaper, in terms of time, than using shuffle). In other words, the following code : for ($i = 0; $i */ srand(); $tirage_tab = array_rand($valeurs, 10); foreach($tirage_tab as $key => $value) { $proba[$valeurs[$value]]++; } } doesn't have the strange behaviour you noticed. No PRNG is perfectly random, so taking the habit of calling srand() from time to time is still a good practice if you rely on a lot of random numbers.
If you're just trying to draw a random subset of n elements from an array, it seems more effecient to do something like this: No messing with indexes when you're done... you just have an array with the elements you're looking for in it.
if you want random elements from an array, this worked pretty well for me.
If you want get unique range:
Verified 2015-06-03 -- this function produces VERY uneven "random" distribution.
I wanted to write something that picks a random entry from a 1column-MySQL database - simply Post Of The Moment (potm). I know there surly are many better ways to do it, but I`m rather new to PHP :) Anyway, it`s simple and no-problem working code. Of course I assume your DB exists and you always have something in it. @$link = MySQL_Connect("localhost", "username", "password"); //connect to mysql mySQL_Select_DB("database"); //..to DB @$potms = MySQL_Query("SELECT * FROM potm"); //now we get all from our table and store it MySQL_Close($link); //there`s no need for connection, so we should close it $potm_array = ''; //sets variables to "zero" values $i = 0; while ($entry = MySQL_Fetch_Array($potms)) //now we go through our DB { $potm_array[$i] = $entry; //our temporary array from which we will random pick a field key $i++; //now we increment our field key } $potm_id = array_rand($potw_array); //picks a random key from array $potm = $potm_array[$potm_id]['name_of_the_field']; //now we have stored our Post Of The Moment in $potm ..hope this helps
For those of you thinking that it does not work for num_req = 1, it is because it return a variable and not an array. This mainly cause some problem with people using foreach. The correct way to handle this is explained by that example: // You can then correctly use the foreach, as it require an array to work // If you use foreach with one element, it won't work.
As wazaawazaa600 at msn dot com pointed out, a multi-dimensional array doesn't work with this function. So, I hope I can help someone with this :)
I modified fake_array_rand to always only return 1 element, and did some benchmarks against calling array_rand with the second parameter as 1. I ran 100 samples for each function for each number of elements and took the average result. While the internal array_rand is faster for a small number of elements, it scales very poorly. 1 elements: 2.0619630813599E-05 sec. for array_rand,8.4352493286133E-05 sec. for fake_array_rand 10 elements: 2.1675825119019E-05 sec. for array_rand,8.427619934082E-05 sec. for fake_array_rand 100 elements: 2.9319524765015E-05 sec. for array_rand,8.4599256515503E-05 sec. for fake_array_rand 1000 elements: 0.0001157283782959 sec. for array_rand,8.5572004318237E-05 sec. for fake_array_rand 10000 elements: 0.0016669762134552 sec. for array_rand,8.5201263427734E-05 sec. for fake_array_rand 100000 elements: 0.015599734783173 sec. for array_rand,8.5580348968506E-05 sec. for fake_array_rand 1000000 elements: 0.18011983394623 sec. for array_rand,8.6690187454224E-05 sec. for fake_array_rand
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)