PHP - proper check if $_POST['variable'] is posted

Viewed 7085

I want to check if $_POST['submit'] is posted.

My original code was:

if ($_POST['submit']) { }

But I have a PHP notice with this code - "Undefined index: submit in..."

So to remove the notice I have to write this:

if (isset($_POST['submit'])) { }

But this is pointless because $_POST array is global and it return always true. Also if I want to check if $_POST['submit'] is not 0 without PHP notice I have to write this:

if (isset($_POST['submit']) && $_POST['submit'] != 0) { }

In this particular case I prefer:

if ($_POST['submit']) {}

But here I get the PHP notice.

So which way is the most proper/accepted?

Thank you

5 Answers

As of PHP version 7 there is a new method available called "Null Coalesce Operator". This method saves you time and space in your code.

$submit = $_POST['submit'] ?? '';

If submit key does not exist or is NULL the value of the $submit variable will be an empty string.

This method is not limited to $_POST. It will work for any variable. For example:

echo $my_message ?? 'No message found';

If message was not initialized or is NULL, the statement above will output No message found

There's even more that you can do with a null coalesce operator, documentation link below.

Documentation here

Related