Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit array to 5 items

Tags:

arrays

php

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)); 
like image 966
Jon87 Avatar asked Mar 07 '13 07:03

Jon87


People also ask

How do I limit the number of items in an array?

To limit array size with JavaScript, we can use the array slice method. to define the add function that takes an array a and value x that we prepend to the returned array. We keep the returned array the same size as a by calling slice with 0 and a.

How do I limit an array in PHP?

Use a counter to access the array, increment it in every call and use the modulus operation to write into the array. If your counter has to persist over several calls you have to store it in a session variable or a cookie. The result is a primitive ring buffer that will always contain the last 5 values.

How do I limit array length in typescript?

position: Array<number>; ...it will let you make an array with arbitrary length. However, if you want an array containing numbers with a specific length i.e. 3 for x,y,z components can you make a type with for a fixed length array, something like this? Any help or clarification appreciated!

Is there a limit to an array?

The maximum length of an array is 4,294,967,295 - that is, the maximum unsigned 32-bit integer.


1 Answers

array_slice returns a slice of an array

array_slice($array, 0, 5) // return the first five elements 
like image 170
Nirav Ranpara Avatar answered Sep 18 '22 13:09

Nirav Ranpara