Reputation: 637
Is there a way to use multiple variables inside a $_GET, $_POST or $_SESSION declaration?
For example: $_SESSION['session_array{$i}']
.
$i
being a counter variable so that each array I save has a different name.
I need this for saving multiple associative arrays in the $_SESSION, if there is another way this could be done this would also be helpful.
Upvotes: 1
Views: 289
Reputation: 8191
You can (for $_POST, $_GET, $_SESSION, $_REQUEST
, respectively) do
$_SESSION["session_array{$i}"]
But, you probably are looking for, or should rather do
$_SESSION['session_array'][$i]
Also, don't forget to use session_start()
before trying to use session variables.
Upvotes: 5
Reputation: 17382
For a Session, you can do:
$_SESSION['key']=array('one','two','three');
echo $_SESSION['key'][1] // echos 'two'
For a form submit with post you can add []
to the end of the input name to put it in an array
<form method="POST" action='/' >
<input name='arr[]' type="text" value="a">
<input name='arr[]' type="text" value="b">
<input name='arr[]' type="text" value="c">
</form>
To be accessed like:
echo $_POST['arr'][0] // echos 'a'
Same as with the form, you just add []
to the variable name and it can be accessed as an array.
if you visit www.yoursite.com/index.php?test[]=a&test[]=b
you can do:
echo $_GET['test'][1] // echos 'b'
Upvotes: 1
Reputation: 4778
All of these support multidimensional arrays.
i.e:
$_SESSION['fruit']['apple']['green'];
$_GET['country_list']['US'];
or with variable:
$_GET['count'][$i];
Upvotes: 2
Reputation: 225044
You can store an array in $_SESSION
(I wouldn't recommend doing it in the other ones, though):
$session_array = array();
$session_array[$i] = 'some value';
$_SESSION['session_array'] = $session_array;
http://www.phpriot.com/articles/intro-php-sessions/7 looks like a good intro for you.
Upvotes: 1
Reputation: 72681
Why not just make the array multidimensional:
$_SESSION['session_array'][$i]
Regarding the $_GET
and $_POST
superglobals: You don't want to store stuff into that manually but rather by a get or post request. So that's not really an issue IMHO.
Still you can have a multidimensional $_POST
superglobal when using input form like:
<form method="post" action="">
<input type="text" name="name[]">
<input type="text" name="name[]">
</form>
Upvotes: 0