2014-03-19 231 views
1

如何使用for循環在數組中聲明變量。我在頁面上有3個輸入字段,所以當按下提交按鈕時,它應該處理下面的代碼行。在我的html頁面上,有一些字段命名爲:question1,question2和question3。通過for循環聲明php變量

以下是process.php文件的代碼。由於某種原因它不起作用,我想這裏有幾個錯誤,但我找不到它們。

<?php 

$question = array(); 
for($j=1; $j<4; $j++) { 
    $question[j] = $_POST['question[j]']; 

$result; 
$n=1; 

if($question[j] != "") { 
    $result = $n.'): '.$question[j].'<br/><br/>'; 
    $n++; 
} 
} 

echo $result; 

?> 
+5

變量名應該以'$'爲前綴。你的文字'j'將被解釋爲常量。無論何時不起作用,啓用'error_reporting'。 – mario

+0

對於訪問輸入字段列表,建議在HTML表單中使用數組名稱語法:'' – mario

回答

1

對於初學者來說,陣列零指數的,所以我想你想的:

for($j=0; $j<3; j++) 

除了形成,這不評價j值:

$_POST['question[j]'] 

我想你可能想要這樣的東西:

$_POST["question$j"] 

然而,如果您做了上述索引變化,因爲你的元素被命名爲開始的1而不是0,那麼你需要考慮的是:

$_POST['question' . $j+1] 
2
<?php 

$question = array(); 
$result = ""; 

for($j=1; $j<4; j++) { 
    $question[$j] = $_POST["question$j"]; 

    if($question[$j] != "") { 
     $result .= $j.'): '.htmlentities($question[$j]).'<br/><br/>'; 
    } 
} 

echo $result; 

?> 

儘管你不需要一個數組。

<?php 
$result = ""; 

for($j=1; $j<4; j++) { 
    $result .= $_POST["question$j"]!="" ? htmlentities($_POST["question$j"]).'<br/><br/>':'';   
} 

echo $result; 
?> 
0

您可以使用下面的HTML代碼

<input type="text" name="question[a]" /> 
<input type="text" name="question[b]" /> 
<input type="text" name="question[c]" /> 

與下面的PHP代碼:

foreach($_POST["question"] as $key => $value) 
{ 
    // $key == "a", "b" or "c" 
    // $value == field values 
} 

記住要淨化你的輸入!