Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

Tracking unique page views per user with sessions - storing in an array or separate keys?

Hello, If I want to track unique page views per user, which of the following should I use - For each page (URL) - create a new key-value pair for each page, or, create a single key with the value being an array of URLs?

For example, given the following pages to track:

example.com/page1
example.com/page2
example.com/page3

And given that a user viewed all of them, then store the data like so (Of course it will be updated as the user enter the pages, not all at once like in my example):

$array_of_viewed_pages[] = 'example.com/page1';
$array_of_viewed_pages[] = 'example.com/page2';
$array_of_viewed_pages[] = 'example.com/page3';
session(['unique_views' => $array_of_viewed_pages]);

Or:

session(['example.com/page1' => true]);
session(['example.com/page2' => true]);
session(['example.com/page3' => true]);

I'm just worried that there might be too many sessions created using the second method and with the first method it's only 1 session key. But maybe that doesn't matter because the array itself grows?

Thanks

0 likes
1 reply
LaryAI's avatar
Level 58

Both methods are valid and will work, but using an array to store the URLs is more efficient as it will only use one session key instead of multiple keys. Additionally, it will be easier to manage and manipulate the data in an array.

Here's an example of how to implement this solution:

// Initialize the array if it doesn't exist
if (!session()->has('unique_views')) {
    session(['unique_views' => []]);
}

// Add the current page URL to the array if it doesn't already exist
$currentUrl = request()->url();
if (!in_array($currentUrl, session('unique_views'))) {
    session()->push('unique_views', $currentUrl);
}

This code checks if the unique_views array exists in the session and initializes it if it doesn't. Then, it gets the current page URL and checks if it already exists in the array. If it doesn't, it adds it to the array using the push method.

Note that this code assumes that you're using Laravel and that the session() and request() functions are available. If you're using a different framework or plain PHP, you'll need to adjust the code accordingly.

Please or to participate in this conversation.