HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

PHP: checking for $_GET variables with if statements

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withphpstatementscheckingforvariables_get

Problem

This code gets me where I need to be, but my word it is ugly.

I am checking for the existence of two $_GET variables with if() statements. I am setting the variables to empty strings first so I do not get an error when I echo them back.

$getvar1 ='';
$getvar2 ='';
$np ='';

if(isset($_GET['getvar1'])) $page_id = $_GET['getvar2'];
if(isset($_GET['getvar2'])) $route = $_GET['getvar2']; 

if(($getvar1 == '' && $getvar1 == '') || $getvar1 == '4')  $np = 'np'; 

    echo "$getvar1 $getvar2 $np";


Is there a better way to declare the variables than setting them to empty strings?

Is there a better way to check and set the $_GET variables?

Solution

If it's a small app something like that would probably be better:

$getvar = isset($_GET['getvar']) ? $_GET['getvar'] : 'somedefault';


If you want to test more stuff:

$getvar = isset($_GET['getvar']) && $JUST_PUT_IT_HERE ? $_GET['getvar'] : 'somedefault';

Code Snippets

$getvar = isset($_GET['getvar']) ? $_GET['getvar'] : 'somedefault';
$getvar = isset($_GET['getvar']) && $JUST_PUT_IT_HERE ? $_GET['getvar'] : 'somedefault';

Context

StackExchange Code Review Q#3819, answer score: 4

Revisions (0)

No revisions yet.