0

I pretty newbie to php and javascript but more i am curious about PHP. I want to add elements into a empty array every time i add a new element trough a input form, and after that i want those elements to be displayed in to the browser .The code i use is this

  <form action="index.php" method="POST">
    <input type="text" name="name" placeholder="name"><br><br>
    <input type="submit" name="submit" value="enter"><br><br>
</form>

<?php

if (isset($_POST['submit'])) {
    $_SESSION['names']=array();
    $names=$_SESSION['names'];
    $name=$_POST['name'];


    array_push($names,$name);

    for($i=0;$i<count($names);$i++){
        echo $names[$i];
    }


};

How could i achieve to display every element inside the array that i add trough the input field in php?

4
  • So what's your question?
    – John Conde
    Apr 14, 2019 at 18:37
  • The question is how could i display every element that i add into an array from the form and displayed it in the browser?
    – eliot
    Apr 14, 2019 at 18:41
  • Isn't your code already doing that?
    – John Conde
    Apr 14, 2019 at 18:42
  • No it overwrites the value every time i add a new value into the form ,
    – eliot
    Apr 14, 2019 at 18:46

1 Answer 1

0

You overwrite the value every time because you wipe out the array on every page load: $_SESSION['names']=array();. Instead check to see if that session variable exists (and is an array) first and, if it doesn't, then create it. Otherwise just append to that array.

<form action="index.php" method="POST">
    <input type="text" name="name" placeholder="name"><br><br>
    <input type="submit" name="submit" value="enter"><br><br>
</form>


<?php
session_start();    

if (isset($_POST['submit'])) {
    if (!isset($_SESSION['names']) || !is_array($_SESSION['names'])) {
        $_SESSION['names'] = array();
    }
    $name = $_POST['name'];
    $_SESSION['names'][] = $name;

    $num_names = count($_SESSION['names']);
    for($i=0;$i<$num_names;$i++){
        echo $_SESSION['names'][$i];
    }
};
3
  • No John it still over writes the old values a keep adding different names and still it over writes the old values from the form
    – eliot
    Apr 14, 2019 at 19:05
  • Did you remember to start your session?
    – John Conde
    Apr 14, 2019 at 19:20
  • John i am so sorry i forgot to start the session it was my mistake , indeed the code works very well , that"s what i asked to do . I want to thank you so much , i learned a lot from you code that was very helpful.THANK YOU SO MUCH John
    – eliot
    Apr 14, 2019 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.