doushou3814 2013-12-06 16:37 采纳率: 100%
浏览 20
已采纳

随机数组不能像预期的那样工作

I'm trying to create an array and display some random values. I'm using the following code:

$range = range(10,31);
$rand = array_rand($range,5);
shuffle($rand);

foreach ($rand as $number) {
  $number = (str_pad($number, 2, "0", STR_PAD_LEFT));
  echo $number." ";
} 

I want to generate numbers between 10 and 31 and display 5 of them, but my code still generating numbers between 00 and 31. Why this is happening?

  • 写回答

3条回答 默认 最新

  • duanfei8897 2013-12-06 16:44
    关注

    Since array_rand() returns keys, not values, you have to use them as indexes into the original $range array.

    foreach ($rand as $index) {
      $number = (str_pad($range[$index], 2, "0", STR_PAD_LEFT));
      echo $number." ";
    }
    

    You could also just call shuffle($range) and then iterate over the first 5 elements of $range.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用