phphtmlformsinputname-attribute

PHP creating an array from form input fields


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.


Solution

  • 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>