doulu6314 2019-04-14 18:37
浏览 68
已采纳

我希望能够回显数组中的所有元素?

I pretty newbie to php and javascript but more i am curious about PHP. I want to add elements into a empty array every time i add a new element trough a input form, and after that i want those elements to be displayed in to the browser .The code i use is this

  <form action="index.php" method="POST">
    <input type="text" name="name" placeholder="name"><br><br>
    <input type="submit" name="submit" value="enter"><br><br>
</form>

<?php

if (isset($_POST['submit'])) {
    $_SESSION['names']=array();
    $names=$_SESSION['names'];
    $name=$_POST['name'];


    array_push($names,$name);

    for($i=0;$i<count($names);$i++){
        echo $names[$i];
    }


};

How could i achieve to display every element inside the array that i add trough the input field in php?

  • 写回答

1条回答 默认 最新

  • douzhu7507 2019-04-14 18:49
    关注

    You overwrite the value every time because you wipe out the array on every page load: $_SESSION['names']=array();. Instead check to see if that session variable exists (and is an array) first and, if it doesn't, then create it. Otherwise just append to that array.

    <form action="index.php" method="POST">
        <input type="text" name="name" placeholder="name"><br><br>
        <input type="submit" name="submit" value="enter"><br><br>
    </form>
    
    
    <?php
    session_start();    
    
    if (isset($_POST['submit'])) {
        if (!isset($_SESSION['names']) || !is_array($_SESSION['names'])) {
            $_SESSION['names'] = array();
        }
        $name = $_POST['name'];
        $_SESSION['names'][] = $name;
    
        $num_names = count($_SESSION['names']);
        for($i=0;$i<$num_names;$i++){
            echo $_SESSION['names'][$i];
        }
    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CSS通配符清除内外边距为什么可以覆盖默认样式?
  • ¥15 SPSS分类模型实训题步骤
  • ¥15 求解决扩散模型代码问题
  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥15 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红
  • ¥15 想问问富文本拿到的html怎么转成docx的