anarchOi anarchOi - 2 months ago 13
PHP Question

Limit array to 5 items

I have a code that will add a number to an array each time a page is visited. the numbers are stored in a cookie and are retrieved later.

I would like to keep only the 5 most recent numbers in the array.

if the array is full (5 items) and a new number must be added, then the oldest number must be removed and the most recent items must be kept

here's what i have:

$lastviewedarticles = array();

if (isset($_COOKIE["viewed_articles"]) ) {
$lastviewedarticles = unserialize($_COOKIE["viewed_articles"]);
}

if (!in_array($articleid, $lastviewedarticles)){
$lastviewedarticles[] = $articleid;
}
setcookie("viewed_articles", serialize($lastviewedarticles));

Answer

First of all i think, you need to obtain array length , then if length > or equal to 5, remove first element , and add element to the end of array.

if (!in_array($articleid, $lastviewedarticles)){
    $count = count($lastviewedarticles);
    if($count>=5)
        array_shift($lastviewedarticles);
    $lastviewedarticles[] = $articleid;
}