Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have a number input field and a submit button. The task: when I click the button push the number to the $a array. The number is $weight.

But when I want to push the following number it replaces the number at index 0.


What I have tried:

<pre lang="PHP"><!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Weight loss app</title>

    $a = [];
    if (isset($_POST['submit'])) {
        $weight = $_POST['weight'];
        array_push($a, $weight);
    <form action="" method="post">
        <input type="number" name="weight" id="weight">
        <button type="submit" name="submit">Upload weight</button>

Updated 26-Jan-23 2:29am

1 solution

Your array $a is declared as being empty which is why it takes the first value at your index 0.

If you add a value, say
$a = [12];
and then run your code, notice that 12 is now at index 0 and weight follows the next then at index 1.

You can also run a test on adding another variable, say $b -
$a = [];
$b = 18;
    if (isset($_POST['submit'])) {
        $weight = $_POST['weight'];
        array_push($a, $b, $weight);

Your print will return
Array {[0] = 18 [1] = 10 (or whatever value was passed for $weight}
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900