PHP creating an array from form input fields [clos

2019-08-03 23:32发布

问题:

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.

回答1:

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>


回答2:

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;
  }
}


回答3:

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.



回答4:

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.