0

I want to post all text box responses to results.php and then randomly choose one of the responses to display.

the form:

<form action="results.php" method="post">
<input maxlength="30" name="friend[]" size="30" type="text" placeholder="Enter an option" />
<input maxlength="30" name="friend[]" size="30" type="text" placeholder="Enter an option" />
<input maxlength="30" name="friend[]" size="30" type="text" placeholder="Enter an option" />
<input maxlength="30" name="friend[]" size="30" type="text" placeholder="Enter an option" />
<input type="submit" value="Submit" />

the php contents (obviously wrong, but something like this?)

foreach ($_POST['friend'] as $value) {          
    if ($value) {
      echo mt_rand($value);
    }
}

2 Answers 2

1

You could use array_rand:

$random_input = $_POST['friend'][array_rand($_POST['friend'])];
Sign up to request clarification or add additional context in comments.

4 Comments

Worked perfectly thanks! Can i ask what is the difference between your use of random, and that of Alien's post? Is there one which is more valid or do they both provide the exact same outcome?
@badluckbarry Forget my previous comment, the most important advantage is that you are not limited to sequential numbers starting at 0 for your keys; you can have any kind of array-key (numerical / string) and if you remove items it will still work.
jeroen is right, though for this particular use case it'll always be a 0-index based array.
@AlienWebguy In this case, true, but it might lead to unexpected bugs in the future if someone decides to use for example the friend's id as an array key.
0
echo $_POST['friend'][ rand(0, count($_POST['friend']) - 1) ];

Comments

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.