Last active
August 12, 2018 17:21
-
-
Save adinan-cenci/9ff5d80003ac872c0c4a72dd9e53baf9 to your computer and use it in GitHub Desktop.
A cleaner way to get $_POST and $_GET values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function getKey($key, &$array, $alternative) | |
{ | |
if (! array_key_exists($key, $array)) { | |
return $alternative; | |
} | |
$value = empty($array[$key]) ? $alternative : $array[$key]; | |
if (is_string($value)) { | |
$value = trim($value); | |
} | |
return $value; | |
} | |
//------------------ | |
function post($key, $alternative = null) | |
{ | |
return getKey($key, $_POST, $alternative); | |
} | |
function get($key, $alternative = null) | |
{ | |
return getKey($key, $_GET, $alternative); | |
} | |
function request($key, $alternative = null) | |
{ | |
return getKey($key, $_REQUEST, $alternative); | |
} | |
//------------------ | |
/** | |
* Far better looking than a bunch of ternary operators | |
*/ | |
$page = get('page', 1); | |
$name = post('name', false); | |
$age = post('age', 0); | |
$foo = post('foo', 'bar'); | |
if (! $name) { | |
echo 'Error: Please, tell us your name.'; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment