I have a classifieds website, and when users click on an ad, an array element containing the ad id is set to a cookie.
Then on the main page, the 'last visited ads' is shown.
Problem is, I have a limit on the nr of 'last visited ads' ( set to 10 ).
So, if the cookie array contains more than 10 elements, I want the elements to be replaced one by one.
I have managed to replace only the last element in the array once the cookies-array-length > 10
. But it only keeps overwriting the last element, when I want it to replace next one (last - 1).
Example: Cookie has more than 10 array elements. I click on an ad. Then the ad-id which gets replaced is the last element, ALWAYS. BUT, I want it to replace elements one by one starting from the last. (nr 10, nr 9, nr 8) so that it doesn't overwrite nr 10 all the time.
Here is the code:
if (isset($_COOKIE['watched_ads'])){
$expir = time()+1728000; //20 days
$ad_arr = unserialize($_COOKIE['watched_ads']);
$arr_elem = count($ad_arr);
for ($i=0; $i<$arr_elem; $i++){
if ($ad_arr[$i] == $ad_id) { $ad_in_cookie_exists = 1;
}
}
if ($arr_elem>10 && $ad_in_cookie_exists!=1){
$ad_arr[$arr_elem-1]=$ad_id; // HERE IS THE PROBLEM, IT REPLACES LAST ONE, CANT FIGURE OUT HOW TO REPLACE ONE BY ONE!
setcookie('watched_ads', serialize($ad_arr), $expir, '/');
}
else if ($ad_in_cookie_exists !=1 && $arr_elem<=10){
$ad_arr[] = $ad_id; echo "andra";
setcookie('watched_ads', serialize($ad_arr), $expir, '/');
}
}
So, do you have any ideas on how to solve this?
Thanks
PS: if you need more input, tell me and I will update the Q!