How can global arrays be effectively utilized in PHP for storing and retrieving user selections?

Global arrays in PHP can be effectively utilized to store user selections by defining an array variable as global within a function where the user selections are being processed. This allows the array to retain its values across different function calls and scripts, making it easy to store and retrieve user selections throughout the application.

<?php
// Define a global array variable to store user selections
global $userSelections;
$userSelections = [];

// Function to process user selections and add them to the global array
function processUserSelection($selection) {
    global $userSelections;
    $userSelections[] = $selection;
}

// Example of storing user selections
processUserSelection('Option 1');
processUserSelection('Option 2');

// Retrieve user selections from the global array
foreach ($userSelections as $selection) {
    echo $selection . "\n";
}
?>