I was wondering whether is another way to check if a variable coming from user input is set and not null, besides (the obvious choice) isset(). In some cases, we may not be using $_POST to get the value, but some similar custom function. isset() can not be used on the result of a function call, so an alternative way to perform the same check must be made. Now, isset() verifies two things:
$variable = NULL;
) and getting a null value due to empty input fields. Or at least so I read.So, is there a good way of checking both these requirements without using isset() ?
The equivalent of isset($var)
for a function return value is func() === null
.
isset
basically does a !== null
comparison, without throwing an error if the tested variable does not exist. This is a non-issue for function return values, since a) functions must exist (or PHP will exit with a fatal error) and b) a function always returns something, at least null
. So all you really need to do is to check for null
, no isset
necessary.
I've written about this extensively here: The Definitive Guide To PHP's isset And empty.
Beyond this, it depends on what exactly you want to check:
isset($_POST['key'])
== false
: !empty($_POST['key'])
isset($_POST['key']) && strlen($_POST['key'])
filter_input