Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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);
@gavinblair
Copy link

gavinblair commented Jun 8, 2010

So you would use this method for all selects in your views, regardless of number of options?

@SeanJA
Copy link
Author

SeanJA commented Jun 8, 2010

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).

@gavinblair
Copy link

gavinblair commented Jun 8, 2010

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.

@SeanJA
Copy link
Author

SeanJA commented Jun 8, 2010

Ya, I think that might be excessive... I like simple in and out functions that do one thing.

@gavinblair
Copy link

gavinblair commented Jun 8, 2010

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.

@SeanJA
Copy link
Author

SeanJA commented Jun 8, 2010

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment