Search code examples
phphtmlarrayssessionunset

Unset certain items from session array when they're clicked?


What I'm basically looking for is the ability to remove a certain item from the array when that item is clicked, for this instance... If I hit "Two", it will disappear.

Demo: http://query.notesquare.me

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
    ini_set("session.save_path", "/home/kucerajacob/public_html/query.notesquare.me/test-sessions");
    session_start();

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $create_playlist = $_POST['create_playlist'];

        $_SESSION['user_playlists'][] = $create_playlist;
    }

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

    if (isset($_SESSION['user_playlists'])) {
        for ($i = 0; $i < count($_SESSION['user_playlists']); $i++) {
            array_unshift($playlists, $_SESSION['user_playlists'][$i]);
        }
    }

    $_SESSION['main'] = $playlists;

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

Solution

  • Its possible, you'll need to handle that request as well. If you want the click posted, a simple <button> next to that should suffice.

    Upon rendering the markup, (of course using the session array) use the key which can be used in unsetting the values.

    <?php
    
    // initialization
    if(empty($_SESSION['user_playlists'])) {
        $_SESSION['user_playlists'] = array("One", "Two", "Three");
    }
    
    if(isset($_POST['add'], $_POST['create_playlist'])) {
        // handle additions
        $_SESSION['user_playlists'][] = $_POST['create_playlist'];
    }
    
    if(isset($_POST['remove'])) {
        // handle remove
        $key = $_POST['remove'];
        unset($_SESSION['user_playlists'][$key]);
    }
    
    ?>
    
    <form method="post">
        <input type="text" id="input-create-playlist" placeholder="Playlist Name" name="create_playlist" />
        <input type="submit" id="button-create-playlist" name="add" value="Create Playlist" />
        <hr/>
        <?php foreach($_SESSION['user_playlists'] as $k => $p): ?>
            <?php echo $p; ?>&nbsp;<button type="submit" name="remove" value="<?php echo $k; ?>">Remove</button><br/>
        <?php endforeach; ?>
    </form>
    

    Sample Demo