Home > Article > Backend Development > How to Store Arrays as Session Variables in PHP: Keeping Data Across Multiple Pages?
Storing Arrays as Session Variables in PHP
When handling web applications, it's often necessary to store data across multiple pages. PHP provides session variables as a means of storing user-specific information throughout their browsing session. The session variable can contain various types of data, including arrays.
Storing an Array in a Session Variable
To store an array as a session variable, simply use array assignment:
<code class="php">$_SESSION['my_array'] = [1, 2, 3, 4, 5];</code>
This will create a session variable named "my_array" and store the given array in it.
Your Specific Scenario
In your case, you have an array representing a list of names on page 2. When this page is submitted, you want the array to be stored in a session variable. To achieve this, you can use:
<code class="php">$_SESSION['names'] = $_POST['names'];</code>
This will save the array of names submitted from the form into a session variable named "names."
Behavior When Returning to Page 1
If you return to page 1 and click another cell, the session array ("names") will retain the values assigned on page 2 unless you explicitly change them or unset the session variable. This is because session variables persist until they are modified or removed.
The above is the detailed content of How to Store Arrays as Session Variables in PHP: Keeping Data Across Multiple Pages?. For more information, please follow other related articles on the PHP Chinese website!