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];
        }
    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!