doutao4480 2019-07-16 19:34
浏览 427
已采纳

从数组中随机选择

There is this function :

mt_rand(1,5)

=> randomly selects between 1 and 5.

and another method:

$items = array(1, 4, 5, 7, 8);
echo $items[array_rand($items)];

My question is about second method. I want to use it in this way. echo array_rand(1,4,5,7,8);

Is there a way to do this, or how can I do it? I would like to use the function without defining the array first. Everything in one place. thanks!

Note: I want to use it for unordered list.

  • 写回答

2条回答 默认 最新

  • doudi4137 2019-07-16 19:37
    关注

    You can flip the array, then use array_rand(), this will inverse the key-value pairs (so the key becomes the value, and vice-versa). This will mean that when you use array_rand(), you get the new key - which was originally the value.

    echo array_rand(array_flip($items));
    

    If you want to define a function with a variable number of parameters, you can do that too, by using func_get_args().

    function random_value() {
        // If there were no values returned, return false.
        if (func_num_args() == 0) {
            return false;
        }
    
        // Get all the values supplied
        $values = func_get_args();
        $random = array_rand($values);
        return $values[$random];
    }
    

    Though you can just define the array inline, by doing

    echo array_rand(array_flip([1, 3, 7, 8]));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作