[Solved] PHP – proper check if $_POST[‘variable’] is posted

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

Solution #1:

isset($_POST['submit']) checks if the submit key is set in the $_POST array. It doesn’t just check whether the $_POST array exists and is therefore not “pointless”. If you want to check whether the value is not falsey (== false), which includes 0, without triggering an error, that’s what empty is for:

if (!empty($_POST['submit']))

which is the same thing as

if ($_POST['submit'])

but without triggering a notice should the value not exist.

See The Definitive Guide To PHP’s isset And empty for an exhaustive explanation.

Respondent: deceze

Solution #2:


Respondent: sumit

Solution #3:

As per my understanding, It should be like below:

if (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST'){
  # if method is post, code goes here.

and if you are sure that your method is POST for sure. and you have data post in $_POST you can use code like below:

if (isset($_POST['submit']) && $_POST['submit'] != '') {# I think, '' instead of 0
  # if data is posted, code goes here.

I usually prefer $_POST.

Solution #4:

$_POST[] checks to see if a variable is submitted and not the form name.

if ( isset($_POST['name']) ) {
    // work here
Respondent: Cyril Joudieh

Solution #5:

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

Respondent: Dimich

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy