0

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?

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, this was the code I was looking for thanks again!
0

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

1 Comment

Thanks for your answer but I already got the right code from the first answer.
0

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.

1 Comment

Thanks for your answer but I already got the right code from the first answer.

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.