1

I want to add my $_POST variable to my array every time I submit a name. With this code it empties the array every time I use the Form. How should I do this if I want to add to the array everytime I submit a name?

<?php
    $array = array();

    if (isset($_POST['name'])){
        $new_name = $_POST['name'];

        array_push($array, $new_name);
    }

    print_r($array);
?>

<form action="index.php" method="POST">
    <input type="text" name="name">
</form>

1 Answer 1

2

See you need something that will remember what $array was, even after a refresh. So either you would need to save it in a database / cookie.

Here is an example using a session ($_SESSION).

<?php
session_start();
if(!isset($_SESSION['names'])){
    $_SESSION['names'] = array();
}
if (isset($_POST['name'])){
    $_SESSION['names'][] = $_POST['name'];
}
foreach($_SESSION['names'] as $name){
    echo $name . '<br>';
}
?>

<form action="index.php" method="POST">
    <input type="text" name="name">
</form>

If you don't understand anything, please do ask.

Sign up to request clarification or add additional context in comments.

8 Comments

So how would I destroy this array if someone closes the site? I'm making a system in which the site chooses 3 people at random. The persons are provided by the person.
The session is unique to each browser, it will not be visible to other users.
Do you need it to be?
OK! What would be the best way to only display the names and not the array(3) { [0]=> string(4) "Steve" [1]=> string(4) "Bill" [2]=> string(5) "Mark" }
Thank you so much for helping!
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.