Previously my code looked like this:
for ($i=0, $n=sizeof($values); $i<$n; $i++) {
$field .= '<option value="' . xtc_parse_input_field_data($values[$i]['id'], array('"' => '"')) . '"';
if ($default == $values[$i]['id']) {
$field .= ' selected="selected"';
}
$field .= '>' . xtc_parse_input_field_data($values[$i]['text'], array('"' => '"', '\'' => ''', '<' => '<', '>' => '>')) . '</option>';
}
Following some advice I changed it to:
if (is_array($values) && count($values) > 0) {
foreach ($values as $value) {
$field .= '<option value="' . xtc_parse_input_field_data($value['id'], array('"' => '"')) . '"';
if ($default == $value['id']) {
$field .= ' selected="selected"';
}
$field .= '>' . xtc_parse_input_field_data($value['text'], array('"' => '"', '\'' => ''', '<' => '<', '>' => '>')) . '</option>';
}
}
But the error remains:
Notice: Undefined index: id in E:\xampp\htdocs\testshop\inc\xtc_draw_pull_down_menu.inc.php
What's causing this error?
I would say that the warning basically does not have anything to do with the piece of code that you have pasted, rather it has to do with the fact that $value
does not have an index named id
in the first place. So in order to fix it you have to check at the source - the place where $values
is generated/stored, to see why there are some values without id.
Having said that, in order to prevent the unwanted notice in your code you can add the following line to test if an index named id
exists, before proceeding:
if(array_key_exists('id',$value)) {
//do all your stuff
}
You can add this just below the line after foreach ($values as $value) {
so that everything you do inside the loop only happens if $value
has an id
element.
However as stated earlier, if you expect every $value
to definitely have an id
, go back to the place where $values
are generated and check whats going on there.