Dealing with types in dynamically-typed languages is always a challenge. Given a variable, does it hold a string? A number? An object? Without inspecting it, you have no idea!

Thus, most of these languages have methods for inspecting variables, where you can ask questions like, “is this a number?” and then decide where to go from there. This can make validating your inputs a bit more difficult.

Of course, this code Joe found might make it more difficult than it needs to be:

        //Return decimal value only
        function get_decimal_value($value){
                try{
                        $result_value = null;
                        if(isset($value)){
                                if(is_numeric($value)){
                                        if(preg_match('/^[0-9]+(\.[0-9]*|)$/', $value)){
                                                $result_value = $value;
                                        }
                                }
                        }
                        return $result_value;
                }catch(Exception $x){
                        echo trim($x->getMessage());
                        return null;
                }
        }

Yes, not only does it check is_numeric, but then it also uses a regex to verify that the string is a number. As an aside, (pattern|) is an unusual way to write an optional section, I’m far more used to (pattern)?, but that’s just nit-picking, and there’s a much larger problem with this code than can be seen from this snipped. I’ll let Joe explain:

This is called on the backend with values straight from DB which are guaranteed to exist and be a number.

That, combined with the bad exception handling? I strongly suspect this is programming by copy/paste.

[Advertisement] Release! is a light card game about software and the people who make it. Play with 2-5 people, or up to 10 with two copies - only $9.95 shipped!