Search code examples
phparray-push

array_push not adding 2nd item after page refresh


I understand that array_push is not adding a 2nd item because when the page refreshes after adding another item the original one goes away and get's replaced by the most recent entry from the text box.

I am trying to achieve this tactic of trying to either...

a. Have a session remember the next item being added EVEN through a page refresh.

or

b. Just not refresh the page at all.

See demo here: http://query.notesquare.me/home.html/

CODE

<form method="post">
    <input type="text" id="input-create-playlist" placeholder="Playlist Name" name="create_playlist" />
    <input type="submit" id="button-create-playlist" value="Create Playlist" />
</form>

<?php
    session_start();

    $create_playlist = $_POST['create_playlist'];

    $playlists = array("One", "Two", "Three");

    $_SESSION['main'] = $playlists;

    array_push($playlists, $create_playlist);

    for ($i = 0; $i < count($playlists); $i++) {
        echo $playlists[$i] . "<br />";
    }
?>

Solution

  • Try

    <form method="post">
        <input type="text" id="input-create-playlist" placeholder="Playlist Name" name="create_playlist" />
        <input type="submit" id="button-create-playlist" value="Create Playlist" />
    </form>
    
    <?php
        session_start();
    
        $create_playlist = $_POST['create_playlist'];
    
        $_SESSION['user_playlists'][] = $create_playlist;
    
        $playlists = array("One", "Two", "Three");
    
        for ($i = 0; $i < count($_SESSION['user_playlists']); $i++) {
            array_push($playlists, $_SESSION['user_playlists'][$i]);
        }
    
        $_SESSION['main'] = $playlists;      
    
        for ($i = 0; $i < count($playlists); $i++) {
            echo $playlists[$i] . "<br />";
        }
    ?>
    

    Your approach was setting the $_SESSION['main'] = $_POST['create_playlist'] before the desired effects of array_push.