Keith Keith - 5 months ago 14
PHP Question

building an array of strings in a SESSION variable (php)

I've got a page (dest.php) as part of a php session, every time a form on another page (source.php) submits to this one, I need to add the strings from the

POST
as another element in a
$_SESSION
variable.

So the idea is that I'll get several
POST
variables (
['name']
,
['gender']
, etc) and need to add them to corresponding
$_SESSION
variable arrays, so the first time the form is submitted, I'll have
$_SESSION['name'][0] = $_POST['name']
and each subsequent submit from source.php will send new
$_POST
variables, and on dest.php, I need to add to the
$_SESSION
arrays such that
end($_SESSION['name']) = $_POST['name']
at all times.

I have a some php later in dest.php that is supposed to echo all the
$_SESSION
variables out in a table, but it's currently treating some of the strings different than others.

<table>
<?php
for($cntr = 0; $cntr < count($_SESSION['name']); $cntr++)
{
echo '<tr><td><input type="button" name="' . $cntr . '" value="edit"></td><td>';
echo $_SESSION['name'][$cntr] .' adopted a ' . $_SESSION['gender'][$cntr] . ', ' . $_SESSION['colors'][$cntr];
echo $_SESSION['species'][$cntr] . ' when visiting ' . $_SESSION['city'][$cntr] . '!' ;
echo '</td></tr>';
}
?>
</table>


For reference, the form is:

<form action="petSentence.php" method="POST" accept-charset="UTF-8">
<table><tr><td>
Your name: <input type="text" name="name"></td></tr><tr><td>
<bold>Pick a city</bold></br>
<input type="radio" name="city" value="Portland"> Portland<br>
<input type="radio" name="city" value="Seattle"> Seattle<br>
<input type="radio" name="city" value="Corvallis"> Corvallis</td><td>
<bold>Pick the color(s)</bold>
<input type="checkbox" name="colors[]" value="brown"> brown<br>
<input type="checkbox" name="colors[]" value="red"> red<br>
<input type="checkbox" name="colors[]" value="green"> green<br>
<input type="checkbox" name="colors[]" value="blue"> blue</td></tr>
<tr><td>
Gender: <select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select></td><td>
What Species:
<select name="species">
<option value="cat">cat</option>
<option value="dog">dog</option>
<option value="bird">bird</option>
<option value="chinchilla">chinchilla</option>
</select></td></tr>
<tr><td><input type="submit" value="Submit"></td></tr>
</table>
</form>


and an example of how I'm building the
$_SESSION
arrays:

if(isset($_SESSION['name']))
{
array_push($_SESSION['name'], $_POST['name']);
}
else
{
$_SESSION['name'] = $_POST['name'];
}
if(isset($_SESSION['gender']))
{
array_push($_SESSION['gender'], $_POST['gender']);
}
else
{
$_SESSION['gender'] = $_POST['gender'];
}


Except the
['name']
variable is printing as expecting, but the
['gender']
array prints as if it's just a big character array.

Answer

Simplify. No need for the ifs and elses:

$_SESSION['name'][]   = $_POST['name'];
$_SESSION['gender'][] = $_POST['gender'];