how to edit |
[eluser]Rick Jolly[/eluser]
You can just add this function to a helper: Code: function int_str($num) See the user guide for info on creating your own helpers. I have a valid.php helper with this and some other validation type functions.
[eluser]onejaguar[/eluser]
Better to just use the PHP built-in function ctype_digit().
[eluser]Chris Newton[/eluser]
ctype_digit; interesting, that's a new one to me. Sweet.
[eluser]Rick Jolly[/eluser]
[quote author="onejaguar" date="1212036174"]Better to just use the PHP built-in function ctype_digit().[/quote] That's the same as is_numeric(), no? How would you confirm an integer?
[eluser]Chris Newton[/eluser]
is_numeric checks to see if it's a number. ctype_digit checks to see if the variable's all digits: 100.1 contains a '.' which is not a number. is_int checks the type as well as the content. A form input is always a string, so ctype_digit will check to see if the string contains only numbers, which is in effect a non-typed integer. If your primary concern is that you're getting an integer value, ctype_digit will work fine. If you also want' to confirm that it's typed as an integer, you'll need to use is_int() as well... if your input is from a form or a uri string, is_int will always fail.
[eluser]Rick Jolly[/eluser]
Ah, so ctype_digit is different than is_numeric. Thanks for educating me. So ctype_digit() will detect a positive integer. Anyone know of a more elegant way of detecting a signed integer than my function?
[eluser]onejaguar[/eluser]
is_numeric($var) will return TRUE if $var is an integer, float, or other numeric type, or any string representation of of a numeric type, which includes a leading +/-, a decimal point, and scientific notation (1.356e5) ctype_digit($var) will return TRUE ONLY if $var is a string AND it contains only digits; and is therefore a positive integer. Not to confuse you, ctype_digit works well for the example above, but be aware that if the variable you are checking is typed as an integer ctype_digit will return false. Code: ctype_digit(5) == FALSE; To detect negative or positive integers I'd do: Code: preg_match("/^\-{0,1}[0-9]+$/", $var) |
Welcome Guest, Not a member yet? Register Sign In |