What is the best practice for storing related values, like article number and quantity, in a session?
When storing related values like article number and quantity in a session, it is best practice to use an associative array to store the values together under a single key. This makes it easier to retrieve and manipulate the related values as needed throughout the session.
// Start the session
session_start();
// Check if the session variable for related values exists
if (!isset($_SESSION['related_values'])) {
$_SESSION['related_values'] = array(); // Initialize an empty array
}
// Add new related values to the session
$article_number = 'ABC123';
$quantity = 5;
$_SESSION['related_values'][$article_number] = $quantity;
// Retrieve and use the related values from the session
foreach ($_SESSION['related_values'] as $article_number => $quantity) {
echo "Article Number: $article_number, Quantity: $quantity <br>";
}