tags:

views:

41

answers:

2

alot of time in programming the value of variables are passed through url parameters, in php;

if (isset($_GET['var'])) {$var = $_GET['var'];}

But if that does not execute, we will have an unset variable, in which may cause errors in the remaining of the code, i usually set the variable to '' or false;

else {$var = '';}

I was wondering what are the best practices, and why : )

thank you!

+1  A: 

I favour using the ?: ternary operator

$var = isset($_GET['var'])) ? $_GET['var'] : 0;

but you can often combine this with code to sanitize your inputs too, e.g. if you're expecting a purely numeric argument:

$var = isset($_GET['var'])) ? intval($_GET['var']) : 0;
Paul Dixon
also very good!
Mohammad
+2  A: 

create a function

function get($name, $default = "") {
   return isset($_GET[$name]) ? $_GET[$name] : $default;
}
r3zn1k
+1 I'm a big fan of creating small functions like this that reduce code size and increase readability.
cletus
thank you this is beautiful : )
Mohammad