-
-
Save SeanJA/429268 to your computer and use it in GitHub Desktop.
<?php | |
/** | |
* Create a select box | |
* @param string $name the name of the select box | |
* @param array $options the options, associative array array('val_1'=>'opt_1' ... ) | |
* @param string $selected the option that is selected | |
* @param array $attributes associative array of attributes for the select box array('attr_1'=>'val_1', 'attr_2'=>'val_2') | |
*/ | |
function html_select($name, array $options, $selected=null, array $attributes = array()) { | |
$select = '<select name=".'.$name.'" '; | |
foreach ($attributes as $a=>$v) { | |
$select .= $a .'="' . $v . '"'; | |
} | |
$select .= ' >'; | |
foreach($options as $oid => $option) { | |
$select .= '<option '; | |
if($selected == $oid) { | |
echo ' selected="selected" '; | |
} | |
$select .= ' value="'.$oid.'">.'.$option.'</option>'; | |
} | |
$select .= '</select>'; | |
echo $select; | |
} | |
$options = array( | |
1 => "Male", | |
2 => "Female" | |
); | |
$attributes = array( | |
'class'=>'simple_selectbox', | |
'disabled'=>'disabled', | |
); | |
html_select('gender', $options, '1', $attributes); |
That's how Drupal does it, with the attributes array. Except with Drupal you create a huge mulidimensional $form array with all your elements and then form_render($form) to output.
Ya, I think that might be excessive... I like simple in and out functions that do one thing.
Do you really have to say "array $options" and "array $attributes = array()" ?
I usually just say "$options" and "$attributes = array()".
I guess it would increase readability.
If you don't do the "array" part I can pass in anything I want, it is just an extra check that php will automagically do for me instead of me having to make sure it is by calling is_array().
It works even better if you have something like:
function (myObject $object){ ... }
If you pass anything other than myObject in it will not work.
Yep Yep Yep... that way it is always the same (granted I would add attributes to the end as an array too, which I did).