Shrp91
Shrp91

Reputation: 163

Entering numbers from form input into an array PHP

<form  method="post" action = "handler.php" > 
<input type="text" name="number1"  /> 
<input type="text" name="number2"  />
<input type="text" name="number3"  />
<input type="text" name="number4"  />
<input type="text" name="number5"  />
 etc..

I have a form set up like this to take in 10 different numbers. I want to add each of these numbers to an array so that I can sort the numbers. I know sort is a built in function but I want to write my own sorting algorithms I just need to get all of numbers into an array so I can pass it my functions.

$numArr = array ();

I have tried everything from array_push to call the $_POST['number1'] directly in the array itself. Every time I do echo $numArr all i get is an empty array as an output.

Upvotes: 1

Views: 4520

Answers (2)

Manish Chauhan
Manish Chauhan

Reputation: 570

You have to use same name of input element and make it an array like,

<form method="post" action="handler.php"> 
  <input type="text" name="numbers[]" /> 
  <input type="text" name="numbers[]" />
  <input type="text" name="numbers[]" />
  <input type="text" name="numbers[]" />
  <input type="text" name="numbers[]" />
</form>

Now, When you submit your form on handler.php you will get an array of numbers[].

$_POST['numbers'];

You can sort array using sort().

$sort_array = sort($_POST['numbers']);

If you print $sort_array then you can see sorted array elements.

Upvotes: 3

djot
djot

Reputation: 2947

<form method="post" action="handler.php"> 
  <input type="text" name="numbers[]" /> 
  <input type="text" name="numbers[]" />
  <input type="text" name="numbers[]" />
  <input type="text" name="numbers[]" />
  <input type="text" name="numbers[]" />
</form>

when submitted...

sort($_POST['numbers']);

Upvotes: 0

Related Questions