RE: [PHP] looping inside of a loop
| From: | Lars Torben Wilson | Date: | Wed, 11 Oct 2000 01:40:22 +0000 |
| Subject: | RE: [PHP] looping inside of a loop | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-19458@lists.php.net to get a copy of this message | ||
Rodney Davis writes:
> It worked wonderfully. Except for the demarkating "selected"
> in the appropiate field. I tried the following:
>
> function writePrefsOptions () {
> $prefs = array( 'something' => 'something_in_japanese',
> 'something_else' =>
> 'something_else_in_japanese');
>
> while (list($option, $value) = each($prefs)) {
> $selected = $option == $form[prefecture] ? 'selected' : '';
> echo "<option value=\"$option\"";
> $selected = $option == $form[prefecture] ? 'selected' : '';
> echo "$selected>$value</option>\n";
> }
> }
>
> $form[prefecture] is the name of the select field.
> I am not too sure why this wouldn't work
> If you have any ideas please let me know.
>
> thanks,
>
> rodney
If that is the actual copy-and-pasted code, then you'll need to
globalize $form before you can access it inside the function. You've
also got the selected test twice; it's only necessary once. Last thing
(I promise): you should quote the array offsets when using associative
arrays; it'll prevent headaches in the future (you can turn up
error_reporting() to catch that sort of thing). Here's a complete
script which works for me:
<form action="" method="post">
<?php
error_reporting(E_ALL);
function writePrefsOptions () {
global $form;
$prefs = array('something' => 'something_in_japanese',
'something_else' => 'something_else_in_japanese');
while (list($option, $value) = each($prefs)) {
$selected = $option == $form['prefecture'] ? ' selected' : '';
echo "<option value=\"$option\"$selected>$value</option>\n";
}
}
echo '<select name="somename">';
$form['prefecture'] = 'something_else'; /* just testing */
writePrefsOptions();
echo '</select>';
?>
</form>
--
+----------------------------------------------------------------+
|Torben Wilson <torben@php.net> Netmill iTech|
|http://www.coastnet.com/~torben http://www.netmill.fi|
|Ph: 1 250 383-9735 torben@netmill.fi|
+----------------------------------------------------------------+