PHP creating an array from form input fields

24.3k Views Asked by At

I'm trying to create an array to store numbers and add them together.

<input type="number" name="numbers[]"/>

I'm getting an undefined variable on the following line

foreach($numbers as $number)

I'm sure this is probably something basic but I'm relatively new to php and help would be greatly appreciated.

4

There are 4 best solutions below

3
On BEST ANSWER

If you want to get the sum of an array you dont need to loop you can use array_sum

Example

<?php
if (isset($_POST['numbers'])) {
    echo array_sum($_POST['numbers']);
}

?>

<form method="POST">
<input type="number" name="numbers[]"/>
<input type="number" name="numbers[]"/>
<input type="number" name="numbers[]"/>
<input type="number" name="numbers[]"/>
<input type="submit" value="add"/>
</form>
0
On

Add some more code, but it basically means that $numbers is not declared yet at this point in the code.

Add this line before:

$numbers = array();

Now it shouldnt give you this error.

So now the question is, where is $numbers supposed to be set? For that we need more info and code.

1
On

If you posted the inputs you're showing from one page to another and you need to run through the list you should set it up like this:

if (isset($_REQUEST['numbers']) && is_array($_REQUEST['numbers'])) {
  $numbers = $_REQUEST['numbers'];

  foreach ($numbers as $number) {
    print $number;
  }
}
4
On

I'm no PHP expert but if I understand you correctly and you are trying to put a variable in an array you would need to say what part of the Array I would assume. I'm pretty sure that $array[i] and $array are not the same and that if you try to put something into $array it will only be able to hold one thing at a time. If you are just gathering a bunch of numbers that someone enters from a form then you could do something like this.

//For the form
<form action="formHandler.php" method="post">
  <input type="text" name="number1">
  <input type="text" name="number2">
  //continue in this manner for as many numbers as you need to gather.
</form>

//for the PHP side of it.
<?php
  $x=1;
  $numbersArray = array();
  for($i=0; $i<10; $i++){
   $numbersArray[$i] = $_POST['number'.$x];
   $x++;
  }
//to add them up
$total=array_sum($numbersArray);
?>

I hope that's right and I hope it helps.