开发者

Get form values into an array in PHP

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=&开发者_StackOverflowquot;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?


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']);
?>


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜