Reputation: 423
How can i store multiple values for a variable in cookie using php, for example $id = 1,2,4,5 Then how can i compare the stored values with a variable? for example, $new_id=4, i want to check if $new_id value exists in the stored values of $id in cookie. Thanks for help and have a nice day.
Upvotes: 0
Views: 8277
Reputation: 356
Here is one out of many solutions (syntax may contain errors):
// Create an array with the values you want to store in the cookie
$id = array(1, 2, 3, 4);
// Create cookie
set_cookie('id', implode(',', $id));
// Get cookie
$id = explode(',', $_COOKIE['id']);
// Test value
if(in_array($newId, $id) === true) {
// Value is in the array
}
Restrictions: The values stored in $id cannot include commas, choose another separator if you need to store commas
Upvotes: 0
Reputation: 1902
to use the multiple value you can use the array and then to store it you can serialize ( and unserialize) the array.
To create array: $array = array(1,2,3,4);
To compare: if (in_array(2,$array)) echo "Yep";
To serialize the data to be stored: $store = serialize($array);
Ten you will be able to create the cookie with $store data and then use unserialize($store) to reconvert data in array.
Upvotes: 0
Reputation: 20721
You can store arbitrary strings in cookie elements, so a serialized array should work. Example:
// To store:
$ids = array(1, 2, 3, 4);
setcookie('ids', serialize($ids));
// To retrieve:
$serialized = $_COOKIE['ids'];
$ids = unserialize($serialized);
// sanity check: $ids needs to be an array.
assert(is_array($ids));
// Now let's check:
if (in_array(4, $ids)) {
// Yes, it's here.
}
A few caveats though:
With these in mind, it might be a better idea to store the array in $_SESSION
instead - this will give you virtually unlimited storage, and the only way for the client application to fiddle with the values is through your code.
Upvotes: 3
Reputation: 3357
Try with following snippet.
// do Stuff to retrieve value of $id from cookie.
// explode variable to array
$idArr = explode(',' , $id);
// check existence of new_id in cookie variable.
if(in_array($new_id , $idArr)){
// new_id exist in cookie variable
}
Hope this will help
Thanks!
Hussain.
Upvotes: 0