Skip to content
Advertisement

Delete elements of a JSON encoded in a $_COOKIE

Good morning! In the code below, I did a programming logic to delete an element in a JSON, but it is encoded within a $_COOKIE.

<?php
  $desire = json_decode($_COOKIE['desire']);
  
  // JSON before deletion from the unset() function
  
  echo print_r($desire)."<hr>";
  
  unset($desire[0]);
  
  $desire = json_decode(print_r($desire))."<hr>";
  
  // JSON after deletion from the unset() function
  
  echo json_encode($desire)[0]."<hr>";
  
  // This function does not work, the variable $_COOKIE ['desire'] remains the same
  
  setcookie('desire', json_encode(json_decode(print_r($desire))), time() + 604800);
?>
Result (html):

Array ( [0] => stdClass Object ( [id_book] => 13 [qtd_book] => 1 [vl_book] => 57.6 ) [1] => stdClass Object ( [id_book] => 20 [qtd_book] => 1 [vl_book] => 105.5 ) ) 1
----------------------------------------------------------------------------------
Array ( [1] => stdClass Object ( [id_book] => 20 [qtd_book] => 1 [vl_book] => 105.5 ) )
----------------------------------------------------------------------------------

QUESTION: What is the most correct way to solve this problem? In the last line of PHP, the setcookie() function does not update the array with the index deleted for the $_COOKIE variable in the page store. Are there other solutions to work with this type of information?

Advertisement

Answer

Last line should simply be:

setcookie('desire', json_encode($desire), time() + 604800);

EDIT: But this line

 $desire = json_decode(print_r($desire))

does not make much sense, it should not be there at all. print_r should be used to display values in a human-readable form and – without a second argument explicitly set to true – its return value does not make much sense.

EDIT #2: Complete cleaned up solution

<?php
  $desire = json_decode($_COOKIE['desire']);
  
  // Value of $desire before unset(). 
  print_r($desire);
  echo '<hr>';
  
  // Unsetting element with index 0.
  // Beware! 0 may not always be the first available index.
  // If removing of the first element is desired, regardless its index, array_shift($desire) should be used instead.
  unset($desire[0]);

  // Value of $desire after unset().
  print_r($desire);
  echo '<hr>';
  
  // Save the new $desire value in the cooke.  
  setcookie('desire', json_encode($desire), time() + 604800);
?>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement