Limit array to 5 items: Keeping track of recent views without bloat
Managing a list of viewed articles by appending new entries to an existing array is a common pattern, but it quickly becomes problematic if you don't enforce a size limit. Without intervention, that list grows indefinitely with every page visit until it consumes significant memory or hits the storage cap of your cookie. The goal here is straightforward: maintain only the five most recent article IDs. When a new ID arrives and the collection already holds five items, the oldest entry must be discarded to make room.
Your current implementation correctly handles the logic of checking for existing entries and preventing duplicates within a single session window:
$lastviewedarticles = array();
if (isset($_COOKIE["viewed_articles"])) {
$lastviewedarticles = unserialize($_COOKIE["viewed_articles"]);
}
if (!in_array($articleid, $lastviewedarticles)) {
$lastviewedarticles[] = $articleid;
}
setcookie("viewed_articles", serialize($lastviewedarticles));
However, the code lacks a mechanism to truncate the array after appending. The critical missing piece is ensuring the array never exceeds five elements. You need to append the new item first, then immediately reduce the count if necessary.
The most direct approach involves using array_slice to keep only the last $N items. This method preserves the order of insertion while discarding the oldest entries:
$lastviewedarticles = array();
if (isset($_COOKIE["viewed_articles"])) {
$lastviewedarticles = unserialize($_COOKIE["viewed_articles"]);
}
// Add the new ID if it doesn't already exist
if (!in_array($articleid, $lastviewedarticles)) {
$lastviewedarticles[] = $articleid;
}
// Limit to 5 items: keep only the last 5 elements
$lastviewedarticles = array_slice($lastviewedarticles, -5);
setcookie("viewed_articles", serialize($lastviewedarticles));
The array_slice function with a negative start index (-5) returns all elements starting from the fifth-to-last one up to the end. This effectively shifts the window of focus to the most recent items. By applying this immediately after the push operation, you ensure the array never grows beyond the limit.
This solution relies on standard PHP functions and avoids external dependencies, making it easy to drop into any project. However, there are trade-offs worth considering when working with cookies for state management. Cookies have strict size limits (typically 4KB). While five integers might seem small, if you plan to store complex objects or longer strings, serialization overhead combined with unbounded growth could hit that ceiling quickly. Enforcing a hard limit is not just about preventing memory leaks; it's about respecting the browser's storage constraints.
Another consideration is concurrency. If multiple requests arrive within a very short timeframe, they might all read the same cookie value, add their items independently, and then write back potentially duplicate entries before any truncation happens. Your current in_array check mitigates this to some degree by preventing immediate duplicates, but race conditions in high-traffic environments can still lead to slight inconsistencies if the window of operation exceeds the time it takes for the server to process requests.
If you are building a larger application framework, you might find that frameworks like Laravel provide built-in helpers for managing state or using queues instead of cookies for tracking views, as they offer better scalability and session handling capabilities. For more advanced needs, such as persisting this data across sessions without hitting cookie limits, consider storing the list in a database or cache store rather than relying on client-side storage.