Jump to content

Create a Dynamtic $_SESSION variable name (by incremental number)


TurtleInAsia

Recommended Posts

Hi,

 

I am trying to improve my old code that controls a shopping list, so that instead of having lots of code it loops until the end is detected. Can someone help me out :-)

 

I have a list of 5 session variables like this:

 

$_SESSION['List']['1']['Title']

$_SESSION['List']['2']['Title']

$_SESSION['List']['3']['Title]

$_SESSION['List']['4']['Title']

$_SESSION['List']['5']['Title']

 

What I currently do is a if else statement like this

 

if (!isset($_SESSION['List']['1']['Title'])) { $_SESSION['List']['1']['Title'] = $_POST['title']; }

elseif (!isset($_SESSION['List']['2']['Title'])) { $_SESSION['List']['2']['Title'] = $_POST['title']; }

elseif (!isset($_SESSION['List']['3']['Title'])) { $_SESSION['List']['3']['Title'] = $_POST['title']; }

elseif (!isset($_SESSION['List']['4']['Title'])) { $_SESSION['List']['4']['Title'] = $_POST['title']; }

elseif (!isset($_SESSION['List']['5']['Title'])) { $_SESSION['List']['5']['Title'] = $_POST['title']; }

 

However this is not good because it is hard coded to a limit of 5.

 

What i want to do it a method of automatically incrementing the number and looping until the number is empty, which will also allow me to have more than 5 entries.

 

Hope that makes sense, any help greatly appreciated :-)

 

Turtle

 

 

that doesnt really loop? wouldnt you want something like

 

$i = 0;
while ($i < /* whatever your limit is */ ){
$_SESSION['List'][i]['Title'] = $_POST['title'];
i++;
}

 

Or is that what you had before and what you want to change it from?

Yes sorry that is my old code I would like to change.

 

I see your new code recommendation and it looks much easier to work with, is there a way to not specify the end number but stop if it reaches a value that is not set ?

 

I am going to try a few things out and will update my results here. Thanks again for the example.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.