John Davidson

Why does looping a session array key in PHP not work compared to explicit declaration

0 comments
Message:


I am new to web development, I am trying an algorithm to loop a session array key in PHP instead of explicit/individual declaration and without the use of actual arrays as I noticed that session array key can be a variable value, here is an example of the code I am working on:


//this doesn't work
for($x=1;$x<4;$x++){
echo "$x".$_REQUEST["'text".$x."'"];
}
//this works
echo "<br>1".$_REQUEST["text1"];
echo "<br>2".$_REQUEST["text2"];
echo "<br>3".$_REQUEST["text3"];

What could be the solution for this?



My Answer:
=5;$x++){
$_SESSION['key'.$x] = $x;
}

//this works
$_SESSION['key1'] = 1;
$_SESSION['key2'] = 2;
$_SESSION['key3'] = 3;
$_SESSION['key4'] = 4;
$_SESSION['key5'] = 5;

The reason why the first code snippet doesn't work is because PHP doesn't support variable variables in the way you are trying to use them with session keys. When you try to access $_SESSION['key'.$x], PHP interprets it as trying to access the key 'key'.$x in the $_SESSION array, rather than concatenating the value of $x to 'key' and accessing that key.

In order to achieve what you are trying to do, you would need to use an actual array to store the values and then loop through that array to set the session keys. Here is an example of how you could do that:

$values = array(1, 2, 3, 4, 5);

foreach($values as $x){
$_SESSION['key'.$x] = $x;
}

This way, you are explicitly declaring an array with the values you want to set as session keys, and then looping through that array to set the session keys.

Rate this post

3 of 5 based on 5716 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us