如何在PHP中随机化?

I'm trying to figure out how to randomize what text shows on a page in PHP.

I'm sure this is very easy but everything I search for related to this is talking about the shuffle() function - which isn't what I want to do.

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".

Any help would be appreciated.

Answer

I guess you mean pseudo-random when using PHP functions.

Also take a look at: 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

Live example: http://codepad.viper-7.com/kuOWNI

Extra

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".

This means, you don't want random. Because when you use true-random it can happen that the output is This is a test 1 every time.

Just shuffle it.:

$page = rand(1, 2);

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

You can put your text in an array, then select a random item from the array using any of a variety of functions.

<?php

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

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

Example: http://codepad.viper-7.com/Vf5oe5

I used count($text) so that if you want to add a third option, you can just add it to the array and not have to worry about further code changes. We -1 from the count() because array keys are numbered from zero.

UPDATE

As Bondye correctly pointed out, you are not asking for random, you are asking for balanced. For that, you'd need to store something on your server, perhaps a toggle or a count, and update that record every time the page is viewed. If this is what you need, you might want to re-frame your question, and provide further detail about what you've attempted so far, along with your server environment (and the back-end database you're using).