CodeIgniter set_select default value

The CodeIgniter documentation is vague on how to set the default value in a select tag when you are using the form helper. There’s a third parameter to the set_select method that’s a boolean.

I recommend using something like the following code snippet:

<select class="form-control" name="email">
 <option value="">None</option>
 <?php foreach ($emails as $option):
 ($option == $userEmail) ? $selected = TRUE:$selected = FALSE;
 <option <?=set_select('email', $option, $selected)?>><?=$option?></option>
 <?php endforeach;?>

So you have to check the value of the $option variable with each iteration of the loop and if it matches another variable (which you should set in your controller) it sets the TRUE that the set_select method requires.

3 Replies to “CodeIgniter set_select default value”

  1. So is this like in simple php would be:
    <option value='’ >

    ? So this is just a complicated way to accomplish something simple like checking for an option’s value, and if it matches, then set it to selected ?

  2. Couldn’t really submit my code, it got cut out, but you can understand my question. Is this just a complicated way to accomplish the simple task of comparing an option’s value to a variable, and if it matches, set it to “selected” ?

Leave a Reply to Attila Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.