I've wrote a simple array, and I would use it to print an html list option set, with a selected element. My problem starts if I try to print multiple lists in my page, because only the first list is printed correctly, why?
<?php
$units = array (
'0' => 'Units',
'kJ' => 'Kilojoule: kJ',
'g' => 'Grams: g',
'mg' => 'Milligrams: mg',
'mcg' => 'Micrograms: mcg, µg');
function unit_select_option ($attributes, $code = "") {
global $units;
$html = "<select title=\"Kilojoule: kJ; Grammi: g; Milligrammi: mg; Microgrammi: mcg, µg;\" $attributes>\r";
while (list($key, $name) = each($units)) {
if ($key == "0") {
$html .= " <option title=\"$name\" value='$key'>$name</option>\r";
} else if ($key == $code) {
$html .= " <option title=\"$name\" selected=\"selected\" value='$key'>$key</option>\r";
} else {
$html .= " <option title=\"$name\" value='$key'>$key</option>\r";
}
}
$html.= "</select>\r";
return $html;
}
print unit_select_option ('class="units_select"', "g");
print unit_select_option ('class="units_select"', "mg");
print unit_select_option ('class="units_select"', "mcg");
?>
the code shouldn't be nothing strange but I haven't found the issue because the page doesn't return any error.
html code:
<select title="Kilojoule: kJ; Grammi: g; Milligrammi: mg; Microgrammi: mcg, µg;" class="units_select">
<option title="Unità" value='0'>Unità</option>
<option title="Kilojoule: kJ" value='kJ'>kJ</option>
<option title="Grammi: g" selected="selected" value='g'>g</option>
<option title="Milligrammi: mg" value='mg'>mg</option>
<option title="Microgrammi: mcg, µg" value='mcg'>mcg</option>
</select>
<select title="Kilojoule: kJ; Grammi: g; Milligrammi: mg; Microgrammi: mcg, µg;" class="units_select">
</select>
<select title="Kilojoule: kJ; Grammi: g; Milligrammi: mg; Microgrammi: mcg, µg;" class="units_select">
</select>
each() advances the internal array cursor. Because $units is a global variable, your first call of unit_select_option() advances the cursor to the end of $units, and there it remains for the subsequent calls.
You need to rewind your array using reset($units); at the end of unit_select_option().
PHP Documentation: reset
You should reset the array pointer: use reset()
But why don't you use a foreach loop?
foreach($units as $key => $name){ ... }
And don't use global, it's evil. Declare $units array as static within the function body.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With