Can i store array in session php?
Array can store more items or data in a single variable but these are not available in different pages for use. Any ordinary ( or normal ) array will loose its data as page execution ends. We have to transfer the array each time the visitor moves away from one page to other. In some applications we need to retain the data as long as the visitor is active at site. Shopping cart is the best example for this. Visitor moves between different pages and adds items to the shopping cart. We have to carry the shopping cart to all the pages along with the visitor. Visitor can add or remove items from the cart from any page. Show
PHP Session variable creating checking and destroying using session_start() using userid and name Demo shopping cart using session array We need a session array to retain the data in different pages. Session arrays are like session variables which maintain a unique link between user's web page and the server. You can read more on session management here. Let us start with declaring a session array. Before that we have to start the session by adding this line at the top of the page
Next, any where inside the page we can declare the array (if not done before ) before using. ( Start the shopping cart ) Here we have declared a session array. We can add elements to it by array_push() function. We can remove items from the array by using array_diff() function. This way we can add or remove
items from out session array. We will use this in our shopping cart script. Multidimensional Session ArrayWe can use multidimensional array to store more than one attributes of an element. We may require to store a product along with the user selection of quantity ( or colour ) in a session array. Here is how to create multidimensional session array
Display elements of the array
Add element to this array
Remove elements to this array We used above codes in our shopping cart script, you can download and check the outputs ARRAY REFERENCE Shopping Cart using Session Array
This is a tutorial on how to store a PHP array in a session variable. Typically, this sort of design is used on eCommerce websites, where the user is able to add multiple products to their cart. Because the cart is a temporary list, many developers will opt to store it in the user’s session. Storing an array in a session variable is simple, and it works exactly the same as storing string values or whatnot. Have a look at the following PHP code snippet:
To make sure that our session array always exists, we could use the following code:
|