Search code examples
phpvalidationisset

Alternative to isset(user_input) in php


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:

  1. Whether the value was set.
  2. Whether the value is null. But there is some difference between assigning a variable the null value ( $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() ?


Solution

  • 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:

    • test if a key was submitted via GET/POST: isset($_POST['key'])
    • test if there's a value and whether it's not == false: !empty($_POST['key'])
    • test if it's a non-empty string: isset($_POST['key']) && strlen($_POST['key'])
    • perhaps much more complex validations: filter_input