0

I want to check values are present in the array and print one random value, but it is giving undefined index error

Here is the code

<?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();
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55

1 Answers1

0

array_rand(array $array [, int $num = 1 ]) returns either an array of keys, if $num is defined and > 1, either a single value.

Since you don't set the second parameter, it returns a single numeric value, being the randomly choosen numeric key of the array, 0 or 1.

Change your code to this to fix that problem :

$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

Cid
  • 14,968
  • 4
  • 30
  • 45