I'm trying to follow the DRY programming philosophy and I am tired of running isset()
and an if not empty
statements for each time I want to check a $_GET[]
variable.
I am working on a page that receives up to 4-5 GET
parameters in the URL, so I wrote the following function to reduce repetitive code:
function getset( $get, $default, $empty=FALSE ) {
// checks if a GET parameter is set
if ( isset($_GET[$get]) ) {
// optionally allows empty values
if ($empty) { return $_GET[$get]; }
// check if value is not empty
else {
if ( $_GET[$get] != '' ) { return $_GET[$get]; }
// otherwise return default value
else { return $default; }
}
}
// if param not set then return default value
else { return $default; }
}
// set the variables
$foo = getset('foo', 'abc');
$bar = getset('bar', 'xyz', TRUE)
// localhost/?foo => returns 'abc'
// localhost/?foo=x => returns 'x'
// localhost/?bar => returns TRUE / ''
I am wondering if my function is proper, efficient and safe compared to the alternative:
// default values
$foo = 'abc';
$bar = '';
// set $foo from $_GET value
if ( isset($_GET['foo']) && $_GET['foo'] != '' ) {
$foo = $_GET['foo'];
}
// set $bar from $_GET value
if ( isset($_GET['bar']) ) {
$bar = $_GET['bar'];
}
I am open to suggestions for improving/refining my code.
empty()
? \$\endgroup\$!= ''
instead. What would it change? \$\endgroup\$empty
may give unexpected results with ie."0"
as a value. It is a function that has to be used with care... \$\endgroup\$"0"
to returnempty
/NULL
. \$\endgroup\$