Keith Keith - 3 months ago 10
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

as another element in a

So the idea is that I'll get several
variables (
, etc) and need to add them to corresponding
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
variables, and on dest.php, I need to add to the
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
variables out in a table, but it's currently treating some of the strings different than others.

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>';

For reference, the form is:

<form action="petSentence.php" method="POST" accept-charset="UTF-8">
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>
Gender: <select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
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>
<tr><td><input type="submit" value="Submit"></td></tr>

and an example of how I'm building the

array_push($_SESSION['name'], $_POST['name']);
$_SESSION['name'] = $_POST['name'];
array_push($_SESSION['gender'], $_POST['gender']);
$_SESSION['gender'] = $_POST['gender'];

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


Simplify. No need for the ifs and elses:

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