To "add" a value to a cookie, all you have to do is read the current value that was sent to you with the current request, add the new data, and set the result as a cookie with the same key.
On each page just change the value of the variable $id
and include the page setar_cookie.php
Pages
$id= "5100";
include("setar_cookie.php");
setar_cookie.php
if(!isset($_COOKIE["itemfavorito"])) {
setcookie("itemfavorito", $id, time()+3600*24*30*12*1, "/");
} else if (strpos($_COOKIE["itemfavorito"],$id)===false){
$addId= $_COOKIE["itemfavorito"]."/".$id;
setcookie("itemfavorito", $addId, time()+3600*24*30*12*1, "/");
}
To remove the right page value
$cookie= $_COOKIE['itemfavorito'];
//exemplo remover 5101
$id= join('/',array_diff(explode('/', $cookie), array('5101')));
setcookie("itemfavorito", $id, time()+3600*24*30*12*1, "/");
no ideone
OBS: The /
(slash) in setcookie
serves to indicate that it works for the whole site and not just the directory where it is being configured setcookie
If you want to keep the cookie always sorted
if(!isset($_COOKIE["itemfavorito"])) {
setcookie("itemfavorito", $id, time()+3600*24*30*12*1, "/");
} else if (strpos($_COOKIE["itemfavorito"],$id)===false){
$addId= $_COOKIE["itemfavorito"]."/".$id;
$array= explode("/",$addId);
sort($array);
$joinId= join('/',$array);
setcookie("itemfavorito", $joinId, time()+3600*24*30*12*1, "/");
}
And if you have a "5101" ID added and if you are adding another "510"
In this case we can use:
setar_cookie.php
$tags = $_COOKIE["itemfavorito"];
$tagsArray = explode('/', $tags);
if(!isset($_COOKIE["itemfavorito"])) {
setcookie("itemfavorito", $id, time()+3600*24*30*12*1, "/");
} else if (!in_array($id, $tagsArray)) {
$addId= $_COOKIE["itemfavorito"]."/".$id;
$array= explode("/",$addId);
sort($array);
$joinId= join('/',$array);
setcookie("itemfavorito", $joinId, time()+3600*24*30*12*1, "/");
}