-1

I would like to print random values in my page. I wrote this code but it is not working:

    $claim[1] = "Red";
    $claim[2] = "Blue";
    $claim[3] = "Yellow";
    $claim[4] = "Purple";
    $claim[5] = "Magenta";
    $color = $claim[mt_rand(1,2,3,4,5)];    

Any idea?

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 1
    *How* does it not work? Do you get an error? If so, what is it? What do you expect to happen? What actually happens? What have you done to debug this? – John Conde Feb 26 '21 at 12:55
  • John I expect the page where I write to print one of the colors above. But it does not print anything – Rendall Narciso Feb 26 '21 at 12:57
  • Where do you come up with `mt_rand(1,2,3,4,5)`? The manual clearly explains with what kind of parameters this function can be called, does it not? You mustn’t wonder that your stuff doesn’t work, when you go and invent your own bogus nonsense syntax. – CBroe Feb 26 '21 at 13:00

1 Answers1

1

You need a random number between 1 to 5:

$claim[1] = "Red";
$claim[2] = "Blue";
$claim[3] = "Yellow";
$claim[4] = "Purple";
$claim[5] = "Magenta";
$color = $claim[rand(1,5)]; 

optional: but you can use array_rand too (Return an array of random keys):

https://www.php.net/manual/en/function.array-rand

$claim[1] = "Red";
$claim[2] = "Blue";
$claim[3] = "Yellow";
$claim[4] = "Purple";
$claim[5] = "Magenta";
$color = $claim[array_rand($claim)]; 
Raskul
  • 1,674
  • 10
  • 26