简体   繁体   中英

Codeigniter weird form_dropdown bug mixed index

I am having a wierd issue with the form_dropdown helper in codeigniter version 2.1.3.

The following code:

print_r($country_options);

echo form_label('Country:','country') . 
form_dropdown('country',$country_options, 0);
...

Outputs

Array ( [0] => All [Australia] => Australia )

<label for="country">Country:</label>
<select name="country">
<option value="0" selected="selected">All</option>
<option value="Australia" selected="selected">Australia</option>
</select>

What am I not seeing?

The problem that instead of only the dropdown 'All' being selected as is set in the third parameter of the form_dropdown function, both dropdown options are being selected even though the second option has a key of 'Australia'

This is a peculiarity in php's in_array function; unfortunately, I can't completely explain it to you, but it revolves around your using the 0 as a key:

The code in the form_helper is:

$sel = (in_array($key, $selected)) ? ' selected="selected"' : '';

where $key = 'Australia' & $selected is actually an array, array(0=>0);

Now, where the weirdness in php occurs is:

Anytime you use a key that will evaluate to false (ie, false, 0, '') you will end up matching all string values. You can play around with different arrays and see.

So, do as Deepanshu recommended & use Array ( [0] => All [1] => Australia )

EDIT: More investigation shows that reason is not 100% correct, but the solution is still valid. I think the issue is simply that the string is being evaluated as a 0 when compared to the array values

More info: Why does PHP consider 0 to be equal to a string?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM