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));
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.
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.
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!
The maximum length of an array is 4,294,967,295 - that is, the maximum unsigned 32-bit integer.
array_slice returns a slice of an array
array_slice($array, 0, 5) // return the first five elements
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With