NYCPHP Meetup

NYPHP.org

[nycphp-talk] Extracting an int from a query string.

dann php at mrmuster.com
Tue Nov 13 12:53:59 EST 2007


This doesn't help get rid of your ternary operator, but I find for  
those times when you absolutely, positively have to have a valid non- 
negative integer ctype_digit() is the way to go. Both is_numeric and  
intval accept the plus sign, the minus sign, a decimal point, the  
letter 'e', and strings in hexidecimal form (intval will turn any  
string with leading digits into an integer, actually). There are some  
issues with casting to an integer, also -- this, for example, gives  
somewhat surprising results:

php -r 'echo (int) 12e90;'

Which is great, if that's what you're looking for, but sometimes you  
already know that the incoming item should be an actual non-negative  
integer and you just want to scrub it to avoid injection attacks or  
random db breakage. Something like this might provide a minor upgrade:

$page_index = ctype_digit($_GET['page']) ? $_GET['page'] :  
$default_page;


dann



More information about the talk mailing list