PHP: a short cut for isset and !empty?
isset && !empty
is redundant. The empty
language construct is basically shorthand for !isset($foo) || !$foo
, with !empty
being equivalent to isset($foo) && $foo
. So you can shorten your code by leaving out the isset
check.
A much simpler way is:
$values = array('pg_title' => null, 'pg_subtitle' => null, …);
$values = array_merge($values, $_POST);
// use $values['pg_title'] etc.
If you don't want your default null
values to be overwritten by falsey values, e.g. ''
, you can do something like this:
$values = array_merge($values, array_filter($_POST));
Just be aware that '0'
is falsey as well.
You can use a simple function
function post_value_or($key, $default = NULL) {
return isset($_POST[$key]) && !empty($_POST[$key]) ? $_POST[$key] : $default;
}
Then use:
$pg_title = post_value_or('pg_title');
// OR with a default
$pg_title = post_value_or('pg_title', 'No Title');
empty($var)
is an abbreviation for !( isset($var) && $var )
.
So !empty($_POST['...'])
will be sufficient for your situation — the isset
call you have currently is redundant.