1
1
1Novocaine2019-11-20 02:42:08
PHP
1Novocaine, 2019-11-20 02:42:08

How to correctly add a condition to exclude the repetition of a value in the $_COOKIE array?

The condition was to sequentially write to the array of cookies id coming from a get request. I came to this option, however, the values ​​written to the array are repeated, which I would like to avoid. An attempt to embed !in_array in the condition results in the array being overwritten in case of a duplicate value.
How can this be corrected?
Thanks in advance.

$cookieValue = []; 
    
    if (isset($_COOKIE['taskId'])) {
        $cookieValue = unserialize($_COOKIE['taskId']);
        array_push($cookieValue, $_GET['id']);
        }
            else 
            array_push($cookieValue, $_GET['id']);
            setcookie('taskId', serialize($cookieValue), time() + 24 * 60 * 60);

Working version, thanks Dmitry .
$cookieValue = []; 
    
   if (isset($_COOKIE['taskId'])) {
        $cookieValue = unserialize($_COOKIE['taskId']);
        array_push($cookieValue, $_GET['id']);
        setcookie('taskId', serialize($cookieValue), time() + 24 * 60 * 60);
        }
            else 
            array_push($cookieValue, $_GET['id']);
            $unique = array_unique($cookieValue);
            setcookie('taskId', serialize($unique), time() + 24 * 60 * 60);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2019-11-20
@1Novocaine

If I understood correctly, then
https://www.php.net/manual/ru/function.array-unique.php should help

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question