Giel Beuzel Giel Beuzel - 4 years ago 129
PHP Question

Adding a variable to an array using a Post Form

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>

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download