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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里