I cannot create dynamic array with Session

Asked

Viewed 270 times

1

My application is the following, words are typed into a form, and the program identifies the amount of characters it has, if that amount is ODD, it adds the word into a table

see how it works, in case the word typed was Jao.

Imagem da aplicação

ai if I add another odd word, it creates the table only with the current word. inserir a descrição da imagem aqui

wanted to know how do I go adding every odd word in the table, without creating a new table just with the current word typed.

follows the code:

<?php
  session_start();
  $_SESSION['var'] = array();
  $_SESSION['tam'] = array();

  function postImpar($nome){

  if((strlen($nome) % 2)!= 0){
    
    array_push($_SESSION['var'], $nome);
    array_push($_SESSION['tam'], strlen($nome));

    }
  }

  echo'<form action="calcula.php" method="post">

    <br />Nome:<input type="text" name="nome" /><br /><br />
       <input type="submit" />

  </form>';


        echo "<h1>Ímpares</h1>";

        echo'<table border="1">';
        if (isset($_POST["nome"])) {

          postImpar($_POST["nome"]);

          $x = $_SESSION['var'];
          $y = $_SESSION['tam'];

          $tam = count($x);

          for($i = 0; $i < $tam; $i++){
            echo "<tr>"."<td>$x[$i]</td>".
            "<td>$y[$i]</td>".
            "</tr>";

        }

    }

      echo"</table>";


 ?>

  • Every time you send a subit is resetting the value of the $_SESSION, remove or comment those lines $_SESSION['var'] = array();&#xA; $_SESSION['tam'] = array();

  • Vlw, for the help was that, I didn’t know I was resetting Thank you, God pay you.

1 answer

2


At the beginning of your code, an empty array is being created. Therefore, whenever the code is started the array is "reset".

Just at the beginning declare as follows:

session_start();
if(!isset($_SESSION['var'])){
    $_SESSION['var'] = array();
}
if(!isset($_SESSION['tam'])){
    $_SESSION['tam'] = array();
}
  • It is true, that was the mistake, thank you very cousin Thank you, God pay you.

  • Nothing, available. Only tags as solved, Abs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.