PHP multiple values in one Form Variable

PHP Best Practices

PHP has some differences in the way it handles multiple form entries.

Date : 2006-04-13
With other languages you can read multiple form variables as a comma seperated list of values which we usually convert into an array with some form of split function. PHP makes this process a little easier but also a little more confusing. Below is a simple PHP page that shows how PHP handles multiple form values in one form field:

<title>Test Select</title>
$names = "";
if (isset($_POST['fieldname'])) {  $names = $_POST['fieldname'];  }
foreach ($names as $value ) {
  echo $value . "<br/>";
<form name="form1" method="post" action="test.php">
<input type="checkbox" name="fieldname[]" value="first_name" CHECKED><br>
<input type="checkbox" name="fieldname[]" value="last_name"><br>
<input type="submit" name="Submit" value="Submit" >

Notice especially the HTML form field description. name="fieldname[]" with most languages you could use the standard name="fieldname". With PHP you need to add the array identifier [] to let PHP know that these multiple fields belong together in an array.

Once these fields are passed to PHP they will be accessible in the $_POST['fieldname'] variable. That variable will be an array that you can then loop through to get at each value.

This may seem odd but it is much easier to use the multiple values from an array than from a string of values.

Comments :

dhill 2007-03-29 #58

Thanks. It's certainly convenient to find this information with a quick Google. When you use a lot of languages, reminders like this are very helpful.

  • Search For Articles