【问题标题】:I want to check values are present in the array and print one random value, but it is giving undefined index error我想检查数组中是否存在值并打印一个随机值,但它给出了未定义的索引错误
【发布时间】:2021-01-06 05:43:21
【问题描述】:

我想检查数组中是否存在值并打印一个随机值,但它给出了未定义的索引错误

这里是代码

<?php

$agents = array(9986344xxx,9663275yyy);
function agent(){
    global $agents;
    if (in_array(9986344xxx,$agents) || in_array(9663275yyy, $agents)) {
        $random = array_rand($agents);
        echo $agents[$random[0]];
     } 
     else{
        echo "notfound";
     }
}

agent();

【问题讨论】:

    标签: php arrays undefined-index


    【解决方案1】:

    array_rand(array $array [, int $num = 1 ]) 返回一个键数组,如果 $num 已定义且 > 1,则返回单个值。

    由于没有设置第二个参数,所以它返回一个数值,即数组中随机选择的数字键,0 或 1。

    将您的代码更改为此以解决该问题:

    $agents = array('9986344xxx','9663275yyy');
    function agent(){
        global $agents;
        if (in_array('9986344xxx',$agents) || in_array('9663275yyy', $agents)) {
            $random = array_rand($agents);
            echo $agents[$random]; // <------------- notice this
         } 
         else{
            echo "notfound";
         }
    }
    
    agent();
    

    fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 2019-12-26
      相关资源
      最近更新 更多