I can not create dynamic array with Session

1

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

See how it works, in case the word you entered was jao.

IfIamtoaddanotheroddword,itcreatesthetableonlywiththecurrentword.

Iwantedtoknowhowtodoitbyaddinginthetableeveryoddword,withoutcreatinganewtablewithonlythecurrentwordentered.

followthecode:

<?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>";


 ?>
    
asked by anonymous 03.08.2016 / 03:53

1 answer

2

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

Just start declaring as follows:

session_start();
if(!isset($_SESSION['var'])){
    $_SESSION['var'] = array();
}
if(!isset($_SESSION['tam'])){
    $_SESSION['tam'] = array();
}
    
03.08.2016 / 05:53