如何在PHP中随机化?

时间:2014-05-07 13:33:09

标签: php

我试图弄清楚如何随机化PHP中页面上显示的文字。

我确信这很容易,但我搜索的与此相关的一切都是在讨论shuffle()函数 - 这不是我想做的事。

我希望有一半的时间人们去我的页面让他们看到"这是一个测试1"他们应该看到的另一半时间"这是一个测试2"。

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:1)

答案

我猜你在使用PHP函数时的意思是pseudo-random

另请查看:http://www.php.net/manual/en/function.array-rand.php

<?php
    $texts = array("a", "b", "c");
    echo $texts[array_rand($texts, 1)]; // Output: a, b or c

实例:http://codepad.viper-7.com/kuOWNI

附加

I want half the time people go to my page for them to see "This is a test 1" and the other half of the time they should see "This is a test 2".

这意味着,您不需要随机。因为当你使用true-random时,每次输出都会This is a test 1

答案 1 :(得分:0)

只是改变它。:

$page = rand(1, 2);

if($page=='1'){
   $website = 'http:/xxxxxx.xxx/';
 }else{
   $website = 'http:/xxxxxx.xxx/';

答案 2 :(得分:0)

您可以将文本放入数组中,然后使用各种函数从数组中选择一个随机项。

<?php

$text = array(
    "This is a test",
    "This is another test"
);

print $text[mt_rand(0,count($text)-1)];

示例:http://codepad.viper-7.com/Vf5oe5

我使用了count($text),所以如果你想添加第三个选项,你可以将它添加到数组中,而不必担心进一步的代码更改。我们-1中的count()因为数组键从零开始编号。

<强>更新

正如Bondye正确指出的那样,你不是要求随机,而是要求平衡。为此,您需要在服务器上存储某些内容,可能是切换或计数,并在每次查看页面时更新该记录。如果这是您所需要的,您可能需要重新构建问题,并提供有关您迄今为止所尝试的内容的更多详细信息,以及您的服务器环境(以及您正在使用的后端数据库) )。