NYCPHP Meetup

NYPHP.org

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

Dan Cech dcech at phpwerx.net
Wed Nov 14 14:43:47 EST 2007


Rob Marscher wrote:
> On Nov 13, 2007, at 3:14 PM, John Campbell wrote:
>> On Nov 13, 2007 2:56 PM, dann <dann at bentobox.net> wrote:
>>> One small caveat I failed to mention earlier: [...snip...]
>>> ctype_digit [...snip...] returns false
>>> if you pass it an actual integer.
>> Easily fixed with:
>> ctype_digit("$int");
>> With the added bonus, that another dev will come behind you, remove
>> the quotes, and create a bug. :)
> 
> Although, you originally said you were using this for request variables
> which are always strings.
> 
> By the way, I've been seeing rumors on the web that the ternary operator
> will support this syntax in PHP6:
> 
> $assigned = isset($somevar) ?: 'default';
> 
> Even less typing!

Still too much typing ;) , try this:

$t = R('test',0,'int');

function R($k,$def = null,$type = null)
{
	if (!isset($_REQUEST[$k])) {
		return $def;
	}
	
	if (isset($type)) {
		return checktype($type,$_REQUEST[$k],$def);
	}
	
	return $_REQUEST[$k];
}

function checktype($type,$v,$def = null)
{
	switch ($type) {
		case 'int':
		case 'integer':
			if ((string)intval($v) !== strval($v)) {
				return $def;
			}
			return intval($v);
		case 'string':
			if (!is_string($v)) {
				return $def;
			}
			break;
	}
	
	return $v;
}

Mix up some additional flavors for $_GET, $_POST, etc and have some real
fun.

Dan



More information about the talk mailing list