Ragnar Lothbrok
Ragnar Lothbrok

Reputation: 67

How to add an element to PHP array without deleting element that is already in array?

I want to add an element to PHP array when form is submitted and then add that array to $_SESSION so I can display it on other page while $_SESSION is active, but when an element is added to an array, element that is already in it is deleted so I constantly have 1 item in array. Any suggestions?

Here's the code:

$korpa = array();
$_SESSION["korpa"] = $korpa;

if(isset($_POST["add"])){
    array_push($korpa, $_POST["id"]);
}

Upvotes: 0

Views: 610

Answers (1)

Qirel
Qirel

Reputation: 26490

You keep assigning an empty array to your session variable, so it will be empty at the start of your script, before you append the POST variable.

Instead, you can append directly to that session variable if the condition is met.

// Initialize the session array if its not set
if (!isset($_SESSION["korpa"])) {
    $_SESSION["korpa"] = [];
}

// Then append the POST value to the session if that's set
if (isset($_POST["add"])) {
    $_SESSION["korpa"][] = $_POST["add"];
}

Naturally you will need to call session_start() at the top of every page using sessions, otherwise they will not be set across your different pages.

Upvotes: 3

Related Questions