Accessing array used in input name for data retention on form error

I’m rewriting a form that was using variables with numbers instead of an array for the names and ids in the input elements. (e.g. agency1, agency2, agency3…)

I know I can do something like:

for ($i = 0; $i < $AMOUNT_OF_AGENCIES; $i++)
<label for="agency<?= $i ?>">Agency Name</label><input type="text" name="agency[]" id="agency<?= $i ?>">

to output the input elements that I need and within an easier to use array, but I would also like to have data retention in case the form errors out because of a validation error in another part of the form.

Can I do this?
<input type="text" name="agency[]" id="agency<?= $i ?>" value="<?= htmlspecialchars($_POST['agency[$i]']) ?>">?

(note: my php syntax may be incorrect in some places, php is not my first language, please forgive me)

I asked the question on Stack Overflow and received the answer, so I’m posting in case anyone else has the question.

Instead of using $_POST['agency[$i]'], it should be $_POST['agency'][$i].

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.