Search code examples
phparrayssessionarray-push

PHP Session Array Duplicating


I'm trying to set a session array with some pre-defined values, which the user can then add to using a simple html form. My problem is that on the page where the array is set, any refresh or revisit of the page just duplicates the pre-defined values within the array. Not only that, but it also overwrites the value coming from the form each time at the end.

So in this basic example, I have a list of animals and a user can add another animal to the list. But this outputs the pre-defined animals again each time i.e. if I submit the form twice (e.g. adding chicken and then dog) I get the output:

Array ( [0] => pig[1] => cow[2] => sheep[3] => chicken[4] => pig[5] => cow[6] => sheep[7] => dog) 

What I want is:

Array ( [0] => pig[1] => cow[2] => sheep[3] => chicken[4] => dog[5])

What am I doing wrong?

index.php

<?php
session_start();
//pre-defined list of animals
$_SESSION['animals'][] = 'pig';
$_SESSION['animals'][] = 'cow';
$_SESSION['animals'][] = 'sheep';
?>

<!--form to add another animal-->
<form action="go.php" method="POST">
  <p><input type="text" name="entry1"></p>
  <p><input type="submit" name="submit"></p>
</form>

go.php

<?php
session_start();
//add form entry1 to the session array
$_SESSION['animals'][] = $_POST['entry1'];

//print session array
print_r($_SESSION['animals']);
?>

Solution

  • Only initialize the session variable if it's not already set:

    if (!isset($_SESSION['animals'])) {
        $_SESSION['animals'] = array('pig', 'cow', 'sheep');
    }