-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?

3
  • 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? Commented Feb 26, 2021 at 12:55
  • John I expect the page where I write <?php echo $color; ?> to print one of the colors above. But it does not print anything Commented Feb 26, 2021 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. Commented Feb 26, 2021 at 13:00

1 Answer 1

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)]; 
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.