0

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?

3 Answers 3

2

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']]);
Sign up to request clarification or add additional context in comments.

Comments

1

Your code already looks fine and almost done.

So I use another array, which stores all your other arrays.

If you now get your $session variable, you can access the wrapper array and get your specific array you want. As you started your array names with 1, but arrays getting called with starting index 1, you have to subtract - 1.

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

$wrapper = array($q1, $q2, $q3);

$session = 2;

foreach ($wrapper[$session-1] as $key) {
 //Will output E, F , G H as session is =2
 echo $key;

}

Comments

1

Recommended

You can use PHP array to do this.

$arr = [
    1 => ['A', 'B', 'C', 'D'],
    2 => ['E', 'F', 'G', 'H'],
    3 => ['I', J', 'K', 'L'],
];

then, access it like:


print_r($arr[$_SESSION['i']]);

Not ready to use Arrays?Well, PHP also allows you to use dynamic variable names, called Variable variables.

$variableName = "q";
//..... Update the value of i in session.

 $variableName .= $_SESSION['i'];// when i = 1, it becomes q1;

 print_r($$variableName); // notice the $$ in the Variable Name
 // output
 // Array (0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D')

Read more about Variable Variables here https://www.php.net/manual/en/language.variables.variable.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.