1

How to declare variables in the array using for loop. I have 3 input fields on my page, so when the submit buttons is pressed, it should process the following line of code. On my html page, there are fields named: question1, question2, and question3.

Here's the code of process.php file. It doesn't work for some reason, I suppose there are several mistakes here but I cannot find em.

<?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;

?>
2
  • 5
    Variable names should be prefixed with a $. Your literal j will be interpreted as constant. Enable error_reporting whenever things don't work. Commented Mar 19, 2014 at 17:05
  • And for accessing a list of input fields, it's advisable to use the array name syntax in your HTML forms: <input name=question[1] ..> Commented Mar 19, 2014 at 17:06

3 Answers 3

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;

?>

Though you don't need an array.

<?php
$result = "";

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

echo $result;
?>
Sign up to request clarification or add additional context in comments.

Comments

1

For starters, arrays are zero-indexed, so I think you want this:

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

Aside form that, this doesn't evaluate the value of j:

$_POST['question[j]']

I think you might want something like this:

$_POST["question$j"]

However, if you made the indexing change above, since your elements are named starting with 1 instead of 0 then you'd need to account for that:

$_POST['question' . $j+1]

Comments

0

You can use following HTML code

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

with following PHP code:

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

Remember to sanitize Your input!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.