Skip to content

Instantly share code, notes, and snippets.

@adinan-cenci
Last active August 12, 2018 17:21
Show Gist options
  • Save adinan-cenci/9ff5d80003ac872c0c4a72dd9e53baf9 to your computer and use it in GitHub Desktop.
Save adinan-cenci/9ff5d80003ac872c0c4a72dd9e53baf9 to your computer and use it in GitHub Desktop.
A cleaner way to get $_POST and $_GET values
<?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