John the Painter John the Painter - 1 year ago 104
PHP Question

PHP isset for optional field data – Undefined index

I'm passing form data into an email to be sent via the server (in this case I am using SendGrid but I think this related specifically to PHP, not the API) and I have a repeatable job section on the form. They can add more than one job on the form to fill out and if they do it simply clones the fields and prepends each field label/name and id with an integer, for example,

and so on. They can add a maximum of 10 jobs.

I'm then passing this into my email template that is being sent. All is well but when it comes to the job section I want to do a check so if
exists for example, then it returns the 8 jobs data.

<?php for ($count = 1; $count <= 10; $count++) : ?>
<?php if (isset($submitted_data['wh-company' . $count . '\''])) : ?>
<p><strong>Work History <?php echo $count; ?></strong><br/>
Company: <?php echo $submitted_data['wh-company' . $count . '\'']; ?><br/>
Position: <?php echo $submitted_data['wh-position' . $count . '\'']; ?><br/>
Company address: <?php echo $submitted_data['wh-address-1' . $count . '\'']; ?><br/>
Date worked from: <?php echo $submitted_data['wh-date-started' . $count . '\'']; ?><br/>
Date worked until: <?php echo $submitted_data['wh-date-ended' . $count . '\'']; ?><br/>
Reasons for leaving: <?php echo $submitted_data['wh-reasons-you-left' . $count . '\'']; ?><br/>
Referee name(s): <?php echo $submitted_data['wh-referee-name' . $count . '\'']; ?><br/>
Referee position: <?php echo $submitted_data['wh-referee-position' . $count . '\'']; ?><br/>
Referee phone number: <?php echo $submitted_data['wh-referee-telephone' . $count . '\'']; ?><br/>
Referee email: <?php echo $submitted_data['wh-referee-email' . $count . '\'']; ?><br/></p>
<?php endif; ?>
<?php endfor; ?>

This is what I have so far. I didn't have
and rather just
if ($submitted_data['wh-company' . $count . '\'']) :
but it returned an
Notice: Undefined index
error for each of the 10 items. I then included the
but now doesn't return anything.

Am I doing anything obviously wrong?

Answer Source

You have no else statement. This means that isset is returning false, the html snippet is skipped and the next iteration of the loop is executed. Because every single isset is failing, noted by the fact that you stated

it returned an Notice: Undefined index error for each of the 10 items

there is no ouptut.


As noted in a comment, adding the ' character is what is causing the Undefined index error while isset is performing its task perfectly, simply use the following:

<?php if (isset($submitted_data['wh-company' . $count])) : ?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download