0

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>';

3 Answers3

3
$_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.

Pedro Caseiro
  • 485
  • 2
  • 11
0
session_start();

if($_GET['saved_name']){

    $_SESSION['saved_names'][] = $_GET['saved_name'];
}
echo '<pre>', print_r($_SESSION['saved_names'], true), '</pre>';
Chukwuemeka Inya
  • 2,575
  • 1
  • 17
  • 23
  • 1
    While this code may answer the question, providing additional context regarding *how* and *why* it solves the problem would improve the answer's long-term value. – Alexander Aug 22 '18 at 16:30
0

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

Nico
  • 6,259
  • 4
  • 24
  • 40