Storing Arrays in PHP Sessions
Let's consider the code we made in the previous lesson:
<?php
if (!empty($_GET)) {
$_SESSION['num1'] = $_GET['num1'];
$_SESSION['num2'] = $_GET['num2'];
}
?>
Actually, we could take and write
all form data at once into $_SESSION:
<?php
if (!empty($_GET)) {
$_SESSION = $_GET;
}
?>
And in the file test2.php do this:
<?php
if (!empty($_SESSION)) {
echo array_sum($_SESSION);
}
?>
The advantage of this approach is that our code will work regardless of the number of inputs in the form.
However, there is also a drawback: by overwriting
$_SESSION we erase all data
that was previously there. Who knows what
another script of ours wrote there? And we will delete it.
Let's do it differently:
<?php
if (!empty($_GET)) {
$_SESSION['nums'] = $_GET;
}
?>
As you can see, we wrote
not just one value into the session variable, but an entire array.
Now in the file test2.php we can find
the sum of the elements of this array:
<?php
if (!empty($_SESSION)) {
echo array_sum($_SESSION['nums']);
}
?>
On one page, using a form, ask
the user for their name, age, salary, and something else.
Store this data in one session variable
in the form of an array. When accessing another
page, iterate through the saved data with a loop
and display each element of the array in its own
li tag of the ul tag.