Limit cookie value to 30

Asked

Viewed 47 times

0

Next I’m with the system to make a history on a site, it saves the id of the page that the user visited, separating the id by comma.

Would it be possible to limit the value to 30 ? example "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30".

And when this value exceeds it begin to update the older ones by replacing the values in descending order? example: "1,2,3.... 29,53"

$id = $_COOKIE["id"];
$novoId = "$cont[id]";

if (!preg_match("/\b{$novoId}\b/", $id)) {
    setcookie("id", $id .= "{$novoId},");
}

$historico = explode(",", $id);

$histanime = array_filter($historico, function($value) {
    /* Retorna apenas os números inteiros */
    return is_numeric($value);
});


$ids5 = implode(",", $histanime) ;

1 answer

1

You can use the explode + array_slice and end with a implode.

$string = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30';
$novoId = 44;

$historico = array_filter(explode(',', $string), function($value) {
    return is_numeric($value);
});

if(in_array($novoId, $historico) === false){
    $historico[] = $novoId;
}

if(($quantidade = count($historico)) > 30){
    $historico = array_slice($historico, $quantidade - 30, 30);
}

$cookie = implode(',', $historico);

setcookie("id", $cookie);

According to the original code $novoId is always inserted at the end, so all of the beginning are the oldest. So we keep adding it to the end, but if there are more than 30 elements we keep only the last 30.

  • if you want to consider the full code, I’ve added it

  • @Gabriel, I made the changes.

  • I added if(($quantity = Count($historico)) > 30){ $historico = array_slice($historico, $quantidade - 30, 30); } to the original code and had the same effect.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.