Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

php - 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));
question from:https://stackoverflow.com/questions/15265723/limit-array-to-5-items

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...