Reputation: 15
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>
Upvotes: 1
Views: 66
Reputation: 605
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.
Upvotes: 2