Search code examples
phpvariablessessionbind

how to bind the value of a variable to another variable in php


I have 3 arrays:

$q1 = ['A', 'B', 'C', 'D'];
$q2 = ['E', 'F', 'G', 'H'];
$q3 = ['I', J', 'K', 'L'];

When i click on submit in a form, i store a session and everytime i click on next, the session will increment with 1

session_start();
if(!isset($_SESSION['i']))  {
    $_SESSION['i'] = 0;
}
if(isset($_POST['next'])){
    $_SESSION['i']++;       
}

$session = $_SESSION['i'];
echo $session;

Now i want to bind the value of the session to the variable $q

So after 1 submit, $q must become $q1, after second submit; $q must become $q2 and so on...

So everytime i submit, the value of the session must be bind to $q, so that i can read different arrays.

(I want to use this for creating a dynamic form:)

foreach ($q as $key => $value) {
...

How can i do that?


Solution

  • Instead of variables - use array:

    // I use explicit indexing, as you start with `i = 1`
    $q = [
        1 => ['A', 'B', 'C', 'D'],
        2 => ['E', 'F', 'G', 'H'],
        3 => ['I', 'J', 'K', 'L'],
    ];
    
    $_SESSION['i'] = 3;
    print_r($q[$_SESSSION['i']]);