Limit cookie value to 30

0

Next I have the system to do a history in a site, it saves the id of the page that the user visited, separating the ids 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 that value exceeds it does 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) ;
    
asked by anonymous 20.02.2018 / 00:08

1 answer

1

You can use explode + array_slice and end with 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 the $novoId is always inserted at the end, so all of the beginning are the oldest. So we continue adding it to the end, but if there are more than 30 elements we keep only the last 30.

    
20.02.2018 / 00:21