SomeGuy SomeGuy - 3 months ago 36
PHP Question

Validating URL query value; switch statement vs in_array?

When it comes to checking if a URL query value is legit, what would be the best method when comparing the two methods below? They both work, but I figured that i'd ask just in case I may have overlooked something.

Switch vs if/else+in_array()

/*
example.com/page/my-value
^ example.com/page.php?q=my-value
*/

$page = null;


# OPTION A
$valid_pages = array('my-value-1', 'my-value-2', 'my-value-3');
if (in_array($_GET['q'], $valid_pages)) {
$page = $_GET['q'];
} else {
header("location: http://www.example.com");
exit;
}

#OPTION B
switch ($_GET['q']) {
case 'my-value-1':
case 'my-value-2':
case 'my-value-3':
$page = $_GET['q'];
break;
default:
header("location: http://www.example.com");
exit;
break;
}


# Do something with $page

Answer

If you're using only a few options, I'd say go for the switch statement. However, this code will be unmanagable when it becomes bigger.

There are functions that are way faster than in_array(). It is actually quite slow, you see.

PHP allows you to name array keys by their strings. If I'm understanding your intentions correctly, you would be better off by setting array keys instead of values, like so;

$valid_pages = array('my-value-1' => '', 'my-value-2' => '', 'my-value-3' => '');

Then you could simply call the proper array key through the $_GET, like so:

if(isset($valid_pages[$_GET['q']]){
  //valid page
}
else{
 //not a valid page,
}

a system like this would not only be lots faster, but also extremely dynamic! This would not break when adding a page to the array. Basically, you'd only have to edit one place instead of 3 places, without having to actually loop through an array every time. (in_array() really is slow!)