Skip to content
PHP Logo

How can the problem of the array being reset to null at each directory change be prevented in the PHP code?

The issue of the array being reset to null at each directory change can be prevented by using sessions in PHP. By storing the array in a session variable, its values will persist across different pages and directory changes. This ensures that the array remains intact and accessible throughout the user's session.

php
<?php
session_start();

// Check if the array is already set in the session
if (!isset($_SESSION['myArray'])) {
    $_SESSION['myArray'] = []; // Initialize the array if it doesn't exist
}

// Add elements to the array
$_SESSION['myArray'][] = "Element 1";
$_SESSION['myArray'][] = "Element 2";

// Access the array
print_r($_SESSION['myArray']);
?>