Jeffrey de Groot
Jeffrey de Groot

Reputation: 3

PHP random text once

I've been looking for the solution of my problem for ages and I still haven't found it so i desided to create a stackoverflow account to ask the question myself.

this is what I created so far:

<? //Chooses a random number $num = Rand (1,2);
switch ($num){
case 1: $retrieved_data = "test"; break;
case 2: $retrieved_data = "test1"; break;
} ?> 

And this is the place where I want the text to appear;

<form enctype="multipart/form-data" action="upload.php" method="POST">
<input name="<?php echo $retrieved_data; ?>" type="file" />
<input name="<?php echo $retrieved_data; ?>" type="file" />
<input type="submit" value="Upload" /></form>

My problem is I want to have the "test1" and "test" randomly displayed on these places but I want them to be different from eachother every time. So if the first input type is "test" I want the second input type to be 'test1" but I can't seem to get this working

Does anyone know what I'm doing wrong or a code to make this possible?

Upvotes: 0

Views: 509

Answers (3)

Shi
Shi

Reputation: 4258

Use array_rand() for that.

$aName = array('test1', 'test2', 'whatever');

function getRandom(array &$aName)
{
    if (($key = array_rand($aName)) === NULL) {
        throw new Exception('No more randomness!');
    }

    $value = $aName[$key];
    unset($aName[$key]);
    return $value;
}

So simply use getRandom($aName) when you need a unique random item from the array.

Upvotes: 0

dev-null-dweller
dev-null-dweller

Reputation: 29462

If you have limited number of possibilities, put them int an array, shuffle it and shift/pop elements from it:

$retrieved_data = array('test', 'test1');
shuffle($retrieved_data);

$random1 = array_shift($retrieved_data);
$random2 = array_shift($retrieved_data);

Upvotes: 3

user1209945
user1209945

Reputation: 81

Step A - you are selecting a number, 1 or 2 Step B - you are running that number through your switch case, this case ONLY takes the number that it receives and assigns it a value. Therefore if your number is 1, your switch case ends at $retrieved_data = "test". If your number is 2 your switch case goes to case 2 and assigns $retrieved_data = "test 1". Step C = $retrieved_data is assigned to your form (it will have only one value, "test" or "test1".

Upvotes: 0

Related Questions