PHP script to store user preferences in a session variable
9. Store Array in Session Variable
Write a PHP script to store an array of user preferences in a session variable.
Sample Solution:
PHP Code :
<?php
session_save_path('i:/custom/');
session_start();
// Array of user preferences
$userPreferences = array(
"theme" => "light",
"language" => "Spanish",
"notifications" => true
);
$_SESSION["preferences"] = $userPreferences;
echo "User preferences have been stored in the session variable 'preferences'.";
?>
Sample Output:
User preferences have been stored in the session variable 'preferences'.
Explanation:
In the above exercise -
- We start the session using session_start() to initialize the session.
- Create an array $userPreferences that represents the user's preferences. This array contains key-value pairs, where each key represents a preference and its corresponding value indicates the user's choice.
- Assign the $userPreferences array to the session variable $_SESSION["preferences"]. This stores the array of user preferences in the session.
- Finally, display a message to confirm that the user preferences have been stored in the session variable named 'preferences'.
When run this script, an array of user preferences will be stored in the session variable. We can access and use this array across different pages or script executions during the session.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to store an array of user preferences in a session variable and then retrieve and display the array.
- Write a PHP function to save an associative array in a session variable and iterate over it to display key-value pairs.
- Write a PHP program to store a multidimensional array in a session and print the array in a formatted table.
- Write a PHP script to update an array stored in a session variable and verify changes across different pages.
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: PHP script to check cookie existence and display a message.
Next: Retrieve and display user preferences in PHP session variable.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.