|
Posted by Chung Leong on 06/21/06 03:15
David Haynes wrote:
> I was just thinking about the millions of times I have done something like:
>
> if( ! empty($foos) ) {
> printf("<select name=\"%s\">\n", $select_name);
> foreach( $foo as $foo ) {
> $selected = ($foo['bah'] == 'xxx' ) ? 'selected' : '';
> printf("<option value=\"%s\" %s>%s</option>\n", $foo['value'],
> $selected, $foo['label']);
> }
> printf("</selected>\n");
> }
>
> and was hoping that it could all be made simpler as something like:
> $attributes = array('name' => 'foo');
> htmlSelect($attributes, $foo);
I usually do this:
<select name="something">
<? foreach($foos as $foo): ?>
<option value="<?=$foo?>" <? selected($val, $foo);
?>><?=$foo?></option>
<? endforeach; ?>
</select>
Where the selected() function echo "selected" if the two parameters are
equal. Doing it this way means I can very easily add in a javascript
handler, add an id, specify a class, add a empty item, and so forth.
The loop structure is also flexible. Sometimes I might use a for() loop
instead.
A function that can handle all the possibilities would be rather
complicated. Chances are you won't remember the parameters. This way,
it's just a matter of knowing your HTML. Friendlier for someone who has
to read your code too.
> in the hopes that the meaning for the page became clearer.
>
> Maybe I'll play with this when I get a little more free time.
>
> -david-
>
> BTW: Why doesn't the foreach() handle the !empty() case? It would make
> more sense IMHO.
Do this:
foreach((array) $clowns as $name => $clown) { }
Null converts to an empty array.
Navigation:
[Reply to this message]
|