doorad
doorad

Reputation: 13

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']);
?>

Upvotes: 1

Views: 317

Answers (3)

Mihir Bhatt
Mihir Bhatt

Reputation: 3155

Check

in_array('YOUR_VALUE',$_SESSION['animals'])

before re inserting it to avoid duplication.
Reference: in_array

Upvotes: 1

W van Rij
W van Rij

Reputation: 536

I would suggest to not insert data in the session directly, but adding hidden input values like:

<input type=hidden name=extraValue[] value="pig">
<input type=hidden name=extraValue[] value="cow">
etc

In your PHP page, unset the previous session since you want a 'fresh' dataset based on the input, not on the old values.

unset($_SESSION['animals']); 

You can access your extra values in $_POST['extraValue']. You then could merge both arrays like

 $postValues = array_merge($_POST['extraValue'], $_POST['entry1']);

I havent tested this code yet, but I would use this 'way', rather than setting SESSION values before input.

Upvotes: 0

Barmar
Barmar

Reputation: 780994

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

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

Upvotes: 2

Related Questions