Save names entered in input in the same variable

0

I am practicing the SESSION_START () in php.

I have an input where to enter names, and I want all the names entered to be saved in the same variable to create a list with all the names entered. This is the code ..

<form action="sesion.php" method="post">
  <label>Nombre: </label><input type="text" name="nombre">
  <br><br>
  <input type="submit" name="BEnviar" value="Enviar">
</form>



<?php
    SESSION_START();

$_SESSION['nombre'] = $_POST['nombre'];
$nombre = $_SESSION['nombre'];

echo "<li>$nombre</li>";
?>

Thank you!

    
asked by davescode 08.11.2018 в 17:02
source

1 answer

1

You can save an array within $_SESSION['nombre'] in this way:

session_start();

// Si existe y es un array ingresamos el nuevo nombre:
if (isset($_SESSION['nombre']) ? is_array($_SESSION['nombre']) : false) {
    array_push($_SESSION['nombre'], $_POST['nombre']);
}
else { // si no es un array (o no existe), lo convertimos en array:
    $_SESSION['nombre'] = array($_POST['nombre']);
}

Then you can show the data like this:

foreach($_SESSION['nombre'] as $nombre) {
    echo "<li>".$nombre."</li>";
}

I hope it serves you.

    
answered by 08.11.2018 / 18:39
source