php获取两个不同的随机数组元素 [英] php get two different random array elements
本文介绍了php获取两个不同的随机数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
来自数组
$my_array = array('a','b','c','d','e');
我想获得两个不同的随机元素.
I want to get two DIFFERENT random elements.
使用以下代码:
for ($i=0; $i<2; $i++) {
$random = array_rand($my_array); # one random array element number
$get_it = $my_array[$random]; # get the letter from the array
echo $get_it;
}
有可能得到两次相同的字母.我需要防止这种情况.我想总是得到两个不同的数组元素.有人能告诉我怎么做吗?谢谢
it is possible to get two times the same letter. I need to prevent this. I want to get always two different array elements. Can somebody tell me how to do that? Thanks
推荐答案
你总是可以删除第一次选择的元素,然后你就不会再选择它.如果您不想修改数组,请创建一个副本.
You could always remove the element that you selected the first time round, then you wouldn't pick it again. If you don't want to modify the array create a copy.
for ($i=0; $i<2; $i++) {
$random = array_rand($my_array); # one random array element number
$get_it = $my_array[$random]; # get the letter from the array
echo $get_it;
unset($my_array[$random]);
}
这篇关于php获取两个不同的随机数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文