user1040259 user1040259 - 1 year ago 67
PHP Question

$_POST data to $_SESSION array

I have a form that allows users to enter a name and an associated date of birth.

The form allows users to dynamically add more names and date of births.

I would like to push this data to an associated array $_SESSION variable and then loop through it.

<form action="page.php">
<input type="text" name="child[0][name]" value="Name">
<input type="text" name="child[0][dob]" value="Date of Birth">
<input type="submit" value="Submit">

//trying to save the posted data to a SESSION
$_SESSION['children'] = [];

if (isset($_POST['child'])) {
foreach ($_POST['child'] as $value) {
array_push($_SESSION['children'], $value['name']);
array_push($_SESSION['children'], $value['dob']);

What would the loop from the SESSION look like to get my data to read:

Peter Smith born on 11/11/1900
Sally Smith born on 11/22/2222

When I print_r($_SESSION):

Array ( [0] => Peter Smith [1] => 11/11/1900 [2] => Sally Smith [3] => 11/22/2222 )

Answer Source

For your current session value, you'd go like this:

$for($i=0; $i<count($_SESSION['children']); $i+=2){
    echo $_SESSION['children'][$i] . ' born on ' . $_SESSION['children'][$i+1] . '<br>';

It would be better if you just kept the keys for a more precise code. Take a look:

// .. code ..
if (isset($_POST['child'])) {
    // check if it's not created yet
        $_SESSION['children'] = array();
    // Adds (without replacing) the values from post to session
    $_SESSION['children'] = array_merge($_SESSION['children'], $_POST['child']);
    // Display the new session data
    foreach($_SESSION['children'] as $v){
        // better access using "name" and "dob"'s keys
        echo $v['name'] . ' was born on ' . $v['dob'] . '<br>';

Note that this code keeps the previous $_SESSION['children'] value.