PHP Shortcuts Episode 1: Simple form/query string values

Hello and welcome to my new mini blog series on PHP shortcuts. I’ll be posting some handy code snippets that I’ve used over the years that will save you both time and possibly also from Repetitive Strain Injury!

First off – A quick function to get a value from both the $_GET or $_POST arrays without potentially throwing errors by forgetting to check if your particular array key exists before trying to access it.

The old, long-winded way:

if(isset($_GET['first_name'])) {
     $first_name = $_GET['first_name'];
} else if(isset($_POST['first_name'])) {
     $first_name = $_POST['first_name'];
} else {
     $first_name = NULL;

if(isset($_GET['last_name'])) {
     $last_name = $_GET['last_name'];
} else if(isset($_POST['last_name'])) {
     $last_name = $_POST['last_name'];
} else {
     $last_name = NULL;

The new, super-quick and easy way:

function get_post($p) {
     if(isset($_GET[$p])) {
          return $_GET[$p];
     } else if(isset($_POST[$p])) {
          return $_POST[$p];
     } else {
          return NULL;

$first_name = get_post('first_name');
$last_name = get_post('last_name');

Job done! See you next time.

Leave a Reply