Search code examples
javascriptsessionsession-state

Storing array in session? How should I do this?


So I have a dynamically created playlist that users create by searching for songs. I want to make it so when the page is refreshed all the songs stay there.

What would be the best way to store the playlist?

I have tried using Persist.js but storing an array like:

[["title":"song name", "artist":"someartist"], ["title":"another song", "artist":"one more"]]

Always makes the array appear as:

["title", "song name", "artist", "someartist", "title"...]

Not what I want. Plus not sure if it is the best idea if the playlist gets large.

So when it be better to create a server session? Or just store all the songs into a database?

Thanks.


Solution

  • You could save the array as a JSON object, which is simply stored as a string. In this way, you can easily store it as a session variable.

    $_SESSION['test'] = json_encode($myArray);
    
    $loadedArray = json_decode($_SESSION['test']);
    

    I'd recommend storing it in a database if you want the list to be stored for any length of time, especially if you don't know how large the list could get. Alternatively, you could just put a cap on the array length and discard all tracks after say the first 20.