CodeIgniter Forums

Full Version: A small helper function to compliment the existing form dropdown helper function.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]Basketcasesoftware[/eluser]
I discovered the documentation was vague on the arguments of the form_dropdown helper function about the item selected argument. I hoped for the best and fed it the display value of the entry I wanted as my default selection. Actually it goes off of the key instead. Since I'm working with rather long lists of option groups (196 countries by region) I needed something a little better. This is a first draft. It functions quite well as far as I've been able to test it.

Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('select_search'))
{
    function select_search($needle,$haystack)
        {
            $selected=array_search($needle,$haystack);

            if ($selected) return $selected;

            foreach ($haystack as $key => $val)
            {
                if(is_array($val))
                {
                    $selected=array_search($needle,$val);
    
                    if($selected) return $selected;
                }
            }
          
           return NULL;
        }
}
?>

I'm open for corrections and improvements. Smile

El Forum

[eluser]theprodigy[/eluser]
First off, nice function.

One quick question though. Can you add an example usage?

Is it as simple as:
Code:
<?php
echo form_dropdown('name', $select_opts, select_search($my_text,$select_opts));
?>

El Forum

[eluser]Basketcasesoftware[/eluser]
@theprodigy - Yep. Just that simple. Other than the need to load the helper file first. I didn't make any suggestions on that part, leaving it to the implementer how they wanted to name it.