Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP filter_input: how to return NULL when it is empty from the input

How can I return NULL with filter_input when the input is empty?

$title = filter_input(INPUT_POST, 'title');
var_dump($title);

it returns,

string '' (length=0)

but I want,

null

Thanks.

like image 880
Run Avatar asked Mar 22 '26 19:03

Run


1 Answers

The NULL should have been FILTER_NULL_ON_FAILURE. But that doesn't do what you want either. Why do you need it to be NULL?

The reason you are getting string (0) is because the post field is available in the form. The field is just empty. If you want it to be NULL the field should not be there.

$foo = filter_input(INPUT_POST, 'foo', FILTER_SANITIZE_STRING, array('options' => array('default' => NULL)));
var_dump($foo);

So go with strlen(). Or make sure the field is not there when you don't need it.

like image 118
tlenss Avatar answered Mar 24 '26 10:03

tlenss