title: PHP - Add value to existing array in cookie on button click
body: <p>I want to add values to the existing array variable inside my cookie.</p>
  
  <p>Currently I set my cookie using Ajax:</p>
  
  <p>Ajax:</p>
  
  <pre><code>function setcookie(productid){
       $.ajax({
              type: 'POST',
              url: "setcookies.php",
              data: {
                  id: "productid"
              },
              success: function (e) {
                  alert(e);
              }
          });
  }
  </code></pre>
  
  <p>PHP setcookies.php</p>
  
  <pre><code>&lt;?php
  $cookiename = "products";
  $cart = array();
  
  $pid = $_POST['id'];
  array_push($cart, $pid);
  
  setcookie($cookiename, serialize($cart), time() + 3600, "/");
  $_COOKIE[$cookiename] = serialize($cart);
  </code></pre>
  
  <p>When I click addproduct button setcookie() function will be called.
  Clicking addproduct button three times I expected that 3 ids of the product should be added to the cookie array but when I access the page that will show the cookies in my page it will just only show the last productid added.</p>
  
  <p>Thank you in advance guys.</p>
  
  <p><strong>EDIT FOR MY WORKING CODE:</strong></p>
  
  <p>Below code works in my end: 
  Just slightly modified the code answered by Dominique.</p>
  
  <pre><code>$cookiename = "products";
  $cart = null;
  $pid = $_POST['id'];
  if (!empty($_COOKIE[$cookiename])) {
      $cart = unserialize($_COOKIE[$cookiename]);
      array_push($cart, $pid);
  } else {
      $cart = array();
      array_push($cart, $pid);
  }
  setcookie($cookiename, serialize($cart), time() + 3600, "/");
  $_COOKIE[$cookiename] = serialize($cart);
  </code></pre>