0

Hello once again stackoverflow. I've been working on something in PHP. Now, what I require is that PHP picks a random value in my array I have and outputs it. But, not make it the same every time, constantly change it everytime the page is loaded.

What I have so far:

    <?php
$a=array("Value 1", "Value 2", "Value 3", "Value 4", "Value 5");
$random_keys=array_rand($a);
echo $random_keys;
?>

Now, I've tried this script but it outputs numbers instead of a value. What is it exactly I am doing wrong?

3 Answers 3

4

Do:

<?php
$a=array("Value 1", "Value 2", "Value 3", "Value 4", "Value 5");
$random_keys=array_rand($a);
echo $a[$random_keys];

array_rand returns the key not the value. You will need to use the key to return the value like above.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! I now see what you mean. Worked perfectly!
@NomadsBoy You are welcome. If you feel that the answer helped you, you can always mark it as the answer. It should help others as well.
2

Alternatively, you could also use the function shuffle(), which re-orders the original array.

$a=array("Value 1", "Value 2", "Value 3", "Value 4", "Value 5");
shuffle($a);
echo $a[0];

Comments

0

It returns the Index so you should write:

$random_keys=$a[array_rand($a)];
echo $random_keys;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.