Question

I have the following function to set a cookie on each indiviual product page a user visits on my website.

function setcookie() {

    $entry_id = '787';

    if (isset($_COOKIE['recently_viewed'])) {

        $currentSession = unserialize($_COOKIE['recently_viewed']);

        if (!in_array($entry_id, $currentSession)) {

            if (count($currentSession) > 5) {
                unset($currentSession[0]);
            }

            $currentSession[] = $entry_id;

        } else {}

        $currentSession = serialize($currentSession);
        setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', '');

    } else {

        $recently_viewed[] = $entry_id;
        $currentSession = serialize($recently_viewed);
        setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', '');

    }

}

In this function I am trying to limit the number of items stored in the cookies array.

When the cookies array has 6 items in it, I want to remove the first (oldest) item in that array and then add the new item (so there is never more than 6 items, but always adds the new one).

I have used the following, but it doesn't always seem to work. Sometimes it removes the first item when there are more than 5, but other times it just keeps adding them so there are more than 6.

if (count($currentSession) > 5) {
    unset($currentSession[0]);
}

Can anyone tell me if there is a better way to achieve this?

Was it helpful?

Solution

You definitely should use session.

session_start();
$entry_id = '788';
if (!is_array($_SESSION['recently_viewed'])) {
    $_SESSION['recently_viewed'] = array();
}
//  add the item to the begining
array_unshift($_SESSION['recently_viewed'], $entry_id);
// ensure unique entries
$_SESSION['recently_viewed'] = array_unique($_SESSION['recently_viewed']);
// keep first 5 entries
$_SESSION['recently_viewed'] = array_slice($_SESSION['recently_viewed'], 0, 5);
echo 'recent: ' . print_r($_SESSION['recently_viewed'], true);

OTHER TIPS

if (count($currentSession) > 5) {
    $arr = array_shift($currentSession);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top