如何在For {}

时间:2016-08-17 10:17:56

标签: php html

我在下面编写代码并输入一个html输入文本:

for($i=0;$i<5;$i++)
 echo '<input type="text" name="subject">';

但是当我想回显那个值时,我输入上面的文本框 它返回“” 没有

echo $_POST['subject'];

我有

<form name="form1"  method="post" action="index.php">

标记此代码的顶部?

对不起,如果我有错误

3 个答案:

答案 0 :(得分:2)

将输入作为数组并使用如下所示的循环读取PHP中的值。

HTML code:

<form name='myForm' action='index.php' method="post">
     <?php
     for {$i=i;$i<5;$i++} {
           echo "<input type='text' name='subject[]'>";
     }
    ?>  
</form>

PHP代码:

$subjectArray = $_POST['subject'];
foreach($subjectArray as $key => $val) {
     if($val != "") {  
         echo $key."==".$val."<br>";
     }
}

答案 1 :(得分:0)

echo HTML代码的方式不好。有人在您之后阅读代码(例如,在公司中)可能会变得非常困难

我建议这样做:

for($i=0;$i<5;$i++) {
    ?><input type="text" name="subject"><?php
}

答案 2 :(得分:0)

如果您想以刚刚输入的形式输入回来,那么您做得太多了。 你的表格也在index.php吗?!如果是,则action="index.php"变为action=""

•使用您的阵列:

$subjectArray= array();
// Gather data from $_POST if it's the subject form
if(!empty($_POST) aa isset $_POST['subjectForm']) {
    // Remove the hidden input from the list
    unset($_POST['subjectForm']);
    // Add the remaining entry to $subjectArray
    foreach($_POST as $key => $value) {
        $subjectArray[$key]= $value;
    }
}

<form name="myForm" action="" method="post">
    <!-- hidden input to find our form after validation -->
    <input type="hidden" name="subjectForm" value=1>
    <?php
    for($i=1; $i<=5; $i++) {
        ?><input type="text" name="subject<?= $i ?>" value="<?php if(isset(subjectArray['subject'.$i])) { echo $_POST['subjectArray'.$i]; } ?>"><?php
    }
    ?>
</form>

•没有你的阵列:

<form name="myForm" action="" method="post">
    <?php
    for($i=1; $i<=5; $i++) {
    ?><input type="text" name="subject<?= $i ?>" value="<?php if(isset($_POST['subject'.$i])) { echo $_POST['subjectArray'.$i]; } ?>"><?php
    }
    ?>
</form>