This question already has an answer here:
For some reason, whenever I try to add something to my array, it just overwrites the index 0, rather than goingto index 1, 2 etc...
Here's my code
//Saved names
session_start();
$saved_names = array();
$_SESSION['saved_names'] = $saved_names;
if($_GET['saved_name']){
$saved_name = $_GET['saved_name'];
$saved_names[] = $saved_name;
}
echo '<pre>', print_r($saved_names, true), '</pre>';
</div>
Others answers are ok-ish, but i like more this solution, it also check if session is just started (so $_SESSION['saved_names']
is not set yet) :
<?php
session_start();
$_SESSION['saved_names'] = isset( $_SESSION['saved_names']) ? $_SESSION['saved_names'] : [];
if($_GET['saved_name']){
$_SESSION['saved_names'][] = $_GET['saved_name'];
}
echo '<pre>', print_r($_SESSION['saved_names'], true), '</pre>';
?>
Edit
@elitepc solution (as he said) is not working because
$saved_names = array(); /empty array
$saved_names = $_SESSION['saved_names']; / <- it has not been declared also will never update
And then
$saved_name = $_GET['saved_name'];
$saved_names[] = $saved_name;
So basically everytime it just creates an empty array and put inside the $_GET
value.
You have to check if the session variable it's been initialized and in case update it with $_GET
value
$_SESSION['saved_names'] = $saved_names;
Is this line correct? did you mean
$saved_names = $_SESSION['saved_names'];
You are resetting the session array and only saving one element, the array will always have length 1.
session_start();
if($_GET['saved_name']){
$_SESSION['saved_names'][] = $_GET['saved_name'];
}
echo '<pre>', print_r($_SESSION['saved_names'], true), '</pre>';