输出随机字符串存储在数组中

输出随机字符串存储在数组中

问题描述:

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?

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.

It returns the Index so you should write:

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

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];