3

Is it possible to get form field values into an array? Example:

<?php
     array('one', 'two', 'three');
?>
<form method="post" action="test.php">
    <input type="hidden" name="test1" value="one" />
    <input type="hidden" name="test2" value="two" />
    <input type="hidden" name="test3" value="three" />
    <input type="submit" value="Test Me" />
</form>

Is it possible to pass all form values no matter the number of them to the array in PHP?

3 Answers 3

13

Yes, just name the inputs the same thing and place brackets after each one:

<form method="post" action="test.php">
    <input type="hidden" name="test[]" value="one" />
    <input type="hidden" name="test[]" value="two" />
    <input type="hidden" name="test[]" value="three" />
    <input type="submit" value="Test Me" />
</form>

Then you can test with:

<?php
    print_r($_POST['test']);
?>
Sign up to request clarification or add additional context in comments.

Comments

12

It already is done.

Look at the $_POST array.

If you do a print_r($_POST); you should see that it is an array.

If you just need the values and not the key, use

$values = array_values($_POST);

Reference: $_POST

2 Comments

Great, how could I get rid of the submit button from the array being posted? And how could I add some elements to the array?
I wouldn't add anything to that array. As for buttons, just leave the name field off.
6

This is actually the way that PHP was designed to work, and one of the reasons it achieved a large market penetration early on with web programming.

When you submit a form to a PHP script, all the form data is put into superglobal arrays that are accessible at any time. So for instance, submitting the form you put in your question:

<form method="post" action="test.php">
    <input type="hidden" name="test1" value="one" />
    <input type="hidden" name="test2" value="two" />
    <input type="hidden" name="test3" value="three" />
    <input type="submit" value="Test Me" />
</form>

would mean that inside test.php, you would have a superglobal named $_POST that would be prefilled as if you had created it with the form data, essentially as follows:

$_POST = array('test1'=>'one', 'test2'=>'two', 'test3'=>'three');

There are superglobals for both POST and GET requests, i.e., $_POST, $_GET. There is one for cookie data, $_COOKIE. There is also $_REQUEST, which contains a combination of all three.

See the documentation page on superglobals for more information.

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.