PHP’s in_array And Loose Typing Grief

I’ve got a small function that builds an HTML select form given a name, array of options, an array of selected options and some javascript options. While looping over the array of options I have a very simple call to PHP’s in_array function to determine if the option currently being looked at is also one of the selected options. The code looks something like this:


           if(in_array($option, $selected_options)) {
               $out .= " selected";
           }

This worked most of the time, but started given me problems under certain conditions. This is where having loose typing in PHP can be a bit of a down side. So my first thought was to simply add true as the third argument to in_array which forces a type comparison as well as a value comparison. This fixed the problem for my previous error conditions, but broke the conditions where it was working before. I thought about adding another argument to my simple function as a hint to know if it should use strict type checking or not. That approach didn’t feel right, I wanted something that would just work. So I threw out the code above completely and replaced it with the following:


            foreach($selected_options as $selected) {
                if("{$option}" == "{$selected}") {
                    $out .= " selected";
                }
            }

In concept this does the same thing as in_array, but the comparison is always done in string context. So far this works under all of the conditions that I’m using it. One of the problem combinations is when 0 (zero) is a valid option. Another problem is when an option could be a number or a letter. With in_array I had to decide which way I wanted to it break, with a simple foreach using string context, both conditions work.

I doubt that this will be the best solution in call cases, but it seems to be working in mine where zero values and type issues were causing me grief. I’ve only been testing this for about 15 minutes, so we’ll see if this stands the test of time as it gets more use.