MNL
MNL

Reputation: 101

Array with only 10 most recent values

I have an array with multiple elements. I want to keep only the 10 most recent values. So I am reversing the array in a loop, checking if the element is within the first 10 range and if not, I unset the element from the array.

Only problem is that the unset does not work. I am using the key to unset the element, but somehow this does not work. The array keeps on growing. Any ideas?

$currentitem = rand(0,100);

$lastproducts = unserialize($_COOKIE['lastproducts']);
$count = 0;

foreach(array_reverse($lastproducts) as $key => $lastproduct) {

    if ($count <= 10) {
        echo "item[$key]: $lastproduct <BR>";       
    }

    else {
        echo "Too many elements. Unsetting item[$key] with value $lastproduct <BR>";
        unset($lastproducts[$key]);
    }

    $count = $count + 1;

}

array_push($lastproducts, $currentitem);

setcookie('lastproducts', serialize($lastproducts), time()+3600);

Upvotes: 1

Views: 602

Answers (4)

David Goodwin
David Goodwin

Reputation: 4318

I'd use array_slice ( http://php.net/array_slice ) perhaps like:

$lastproducts = unserialize($_COOKIE['lastproducts']);
// add on the end ...
$lastproducts[] = $newproduct;
// start at -10 from the end, give me 10 at most 
$lastproducts = array_slice($lastproducts, -10); 
// ....

Upvotes: 1

MNL
MNL

Reputation: 101

Works great using array_splice and array_slice, thanks! :)

$lastproducts = unserialize($_COOKIE['lastproducts']);

// remove this product from array
$lastproducts = array_diff($lastproducts, array($productid));

// insert product on first position in array
array_splice($lastproducts, 0, 0, $productid);

// keep only first 15 products of array
$lastproducts = array_slice($lastproducts, 0, 15);

Upvotes: 0

davidvegacl
davidvegacl

Reputation: 151

I think a better way to select last 10 is:

$selection = array();
foreach(array_reverse($lastproducts) as $key => $lastproduct) {
  $selection[$key] = $lastproduct;
  if (count($selection)>=10) break;
}

Finally, $selection will have last 10 (or less) products.

Upvotes: 0

Wolverine
Wolverine

Reputation: 1702

You can use array_splice($input, $offset) function for this purpose.

$last_items_count = 10;
if(count($lastproducts) >= $last_items_count) {
    $lastproducts = array_splice($lastproducts, count($lastproducts) - $last_items_count);
}

var_dump($lastproducts);

I hope this code helps.

For more information, here is the documentation:

http://php.net/manual/en/function.array-splice.php

Upvotes: 0

Related Questions