donglei1616 2017-10-27 01:24
浏览 48

PHP随机选择非零变量

Say I have 5 variables:

$a=2
$b=0
$c=7
$d=0
$e=3

I want to choose one variable randomly that is not zero, do something with it, then set that chosen variable to zero.

Note that I want to know which variable is chosen, for example if I got 7 I want to also know that it's $c, so that I can change its value after reading it.

What is the simplest way to do that?

I was thinking take all variables then randomize first, then check if it's zero, but it doesn't scale well if I had more variables and more zeroes.

  • 写回答

3条回答 默认 最新

  • dongyong1897 2017-10-27 01:35
    关注

    First, I would recommend crafting an array that contains all of the target values. You can then filter the zero values out with array_filter(). Then select a random index from the filtered array with array_rand().

    You then have a random non-zero value assigned to $filtered_array[$random_index], which you are free to assign to an independent variable, or echo out to the DOM.

    <?php
    
    $a = 2;
    $b = 0;
    $c = 7;
    $d = 0;
    $e = 3;
    
    $array = [$a, $b, $c, $d, $e];
    $filtered_array = array_filter($array);
    $random_index = array_rand($filtered_array);
    
    echo $filtered_array[$random_index]; // 2, 7 or 3
    

    This can be seen working here.

    Hope this helps! :)

    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?