I am trying to take input from a form, add it to an array, and print_r that array to the screen.
My problem is that the input from the form only replaces the first (and only) element in the array.
<form action="" method="POST">
<input type="text" name="text" />
<input type="submit" name="sub"/>
</form>
<?php
$a = array();
if( isset($_REQUEST['text']) && !empty($_REQUEST['text'])){
array_push($a, $_REQUEST['text']);
print_r($a);
}
?>
One theory of mine is that $a keeps getting re-assigned on the first line of PHP code ($a = array();), but I’m not sure how to fix it. I have looked around, but can’t find an answer.
You are correct. The array does get reinitialized each time the form is posted. What you’ll want to do is have your array as a more persistent data source.
$_SESSIONvariable.You might also consider writing this data to a small text file that you could then read at the start of the script.
Another option would be to write the data to a
$_COOKIE.