PHP Arrays Ex. #4: Add User Input to Array

In this PHP exercise, you will create an array, print it to the browser, then ask the user to add to it.

Create an array of modes of transportation, including Automobile, Jet, Ferry, Subway. Print the following statement to the browser: "Travel takes many forms, whether across town, across the country, or around the world. Here is a list of some common modes of transportation:" Follow this with an unordered list created by iterating through the array variable you created.

Next, give the user a text box and ask the user to add other modes of transportation to the list, separated by commas. When the user clicks 'Go', process the input with array functions to send back the original list with the user's additions. Include another text box with the text "Add more?" and another submit button. When the user clicks this button, the page should reload with the new additions added to the previously expanded list. Your code should allow the user to add items as many times as they like.


Here's the code:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  2.      "">
  4. <html xmlns=""  xml:lang="en" lang="en">
  5. <head>
  6. <meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
  7. <title>User Input Added to Array</title>
  8. </head>
  10. <body>
  11. <h2>How Are You Traveling?</h2>
  13. <?php
  14. //If form not submitted, display form.  
  15. if (!isset($_POST['submit'])){
  16. $travel=array(
  17.   "Automobile",
  18.   "Jet",
  19.   "Ferry",
  20.   "Subway"
  21. );
  23. ?>
  25. <p>Travel takes many forms, whether across town, across the country, or
  26.  around the world. Here is a list of some common modes of transportation:</p>
  27. <ul>
  29. <?php
  30. foreach ($travel as $t){
  31.   echo "<li>$t</li>\n"; 
  32. }
  33. ?>
  35. </ul>
  36. <form method="post" action="yourfile.php">
  37. <p>Please add your favorite, local, or even imaginary modes of travel 
  38. to the list, separated by commas:</p>
  39. <input type="text" name="added" size="80" />
  40. <p />
  42. <?php
  43. //Send current travel array as hidden form data.
  44. foreach ($travel as $t){
  45.   echo "<input type=\"hidden\" name=\"travel[]\" value=\"$t\" />\n";
  46. }
  47. ?>
  49. <input type="submit" name="submit" value="Go" />
  50. </form>
  52. <?php
  53. //If form submitted, process input.
  54. }else{
  55. //Retrieve established travel array.
  56. $travel=($_POST['travel']);
  57. //Convert user input string into an array.
  58. $added=explode(',',$_POST['added']);
  60. //Add to the established array.
  61. array_splice($travel, count($travel), 0, $added);
  62. //This could also be written $travel=array_merge($travel, $added);
  64. //Return the new list to the user.
  65. echo "<p>Here is the list with your additions:</p>\n<ul>\n";
  66. foreach($travel as $t){
  67.   //The trim functions deletes extra spaces the user may have entered.
  68.   echo "<li>".trim($t)."</li>\n";  
  69. }
  70. echo"</ul>";  
  72. ?>
  73. <p>Add more?</p>
  74. <form method="post" action="yourfile.php">
  75. <input type="text" name="added" size="80" />
  76. <p />
  77. <?php
  78. //Send current travel array as hidden form data.
  79. foreach ($travel as $t){
  80.   echo "<input type=\"hidden\" name=\"travel[]\" value=\"$t\" />\n";
  81. }
  82. ?>
  83. <input type="submit" name="submit" value="Go" />
  84. </form>
  85. <?php
  86. }
  87. ?>
  88. </body>
  89. </html>

See the output of the script in a separate window here. You can also view the output's HTML source from the new window, if you need to check that.


This is a very good example, and I like your site very much.
This problem has two forms inside it, first on is shown as soon as the webpage is loaded.
And only after its submission, second one with"Add more?" question appears.
How is that done?
I have written the exact same code for different type of user-input, but my result shows both forms as soon as the page is loaded in browser.I would like to know what should I do?

How to do this is explained in PHP Forms Ex. #2: Interactive Form with If-Else Statement. It's also in the code for this exercise, but it might be harder to see there.

Glad you like the site!

Thanks for quick reply.
using (isset['submit']) function makes whether to show the form or not.
But here in your script, two "Go" (submit) buttons are used. The second on is shown only after first one is clicked. I want that same thing in my script, but cannot get that...

That was a really nice exercise :)

is there any other way to call the $travel array directly so I can use it in the else statement other than using this technique?

//Send current travel array as hidden form data.
foreach ($travel as $t){
echo "\n";

//Retrieve established travel array.

thank you for the site, its a big help for beginners like me.

hello I like your site very much.thank you very much.

hello i have problem.array_splice($travel, count($travel), 0, $added)get t_string error.i copy and paste thise program.please helo me.

hey! great site with excellent and practical exercises!!

i need to ask though how i can add a limit of maximum 10 that the user can add only up to 10 new options to the list!


hi there...
hey your site is great with excellent and practical exercises ...
It helped me a lot in learning php....
I request you that can you add more exercises in it, if yes then plz make it....

Best exercises in programming is actually developing applications. Along the way you will be facing problems that you have to solve yourself and from there you can get a lot of discoveries.

Self initiated projects would do.

First of all thank you for a great site.

I am too new to PHP and just learning from here.

In the above code, though the form appears properly after i submit the values, the page doesn't replicate changes.

What am i missing. Do i have update my php software?


I'm new to PHP programming and coded this while resisting to ever look at the solution script that's why its organized differently. It's shorter though and clear and easy to understand at a glance.

  1. 	<?php		
  2. 		echo "Travel takes many form, whether across town, across the country, or around the world. <br/>";
  3. 		echo "Here's a list of some common modes of transportation: <br/> <br/>";			
  5. 		if (empty($_POST['userInput'])) {
  6. 			$transMode=array('Automobile','Jet','Ferry','Subway');
  7. 			$textLabel="<br/>Have something to add? <br/>(Please separate entries with a comma): <br/>";
  8. 		}															
  9. 		else {														//retrieve the users input as well as our
  10. 			$tempString1=explode(',',$_POST['transModeArray']);		//storage array from submitted form.
  11. 			$tempString2=explode(',',$_POST['userInput']);			//convert the comma separated string from
  12. 			$transMode=array_merge($tempString1,$tempString2);		//the user input, and the storage
  13. 			$textLabel="<br/> Add more?<br/>";						//array sent with it, and join them.
  14. 		}
  15. 		foreach ($transMode as $transportMode) 
  16. 			echo "<li>$transportMode</li>";		//show everything we have from our storage array
  17. 		$tempString1=implode(',',$transMode);	//now pack it up, ready for attachment with the form.
  18. 	?>											
  19. 	<form action="" method="post">		
  20. 		<?php echo"$textLabel"; ?>
  21. 		<input type="text" name="userInput" maxlength="500"/>
  22. 		<input type="hidden" name="transModeArray" value="<?php echo"$tempString1"; ?>" /> <br/>
  23. 		<input type="submit" value="Go!">
  24. 	</form>