[php] Check if $_POST exists

I'm trying to check whether a $_POST exists and if it does, print it inside another string, if not, don't print at all.

something like this:

$fromPerson = '+from%3A'.$_POST['fromPerson'];

function fromPerson() {
    if !($_POST['fromPerson']) {
        print ''
    } else {
        print $fromPerson
    };
}

$newString = fromPerson();

Any help would be great!

This question is related to php

The answer is


if( isset($_POST['fromPerson']) ) is right.

You can use a function and return, better then directing echo.


Surprised it has not been mentioned

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['fromPerson'])){

I like to check if it isset and if it's empty in a ternary operator.

// POST variable check
$userID  = (isset( $_POST['userID'] )    && !empty( $_POST['userID'] ))   ? $_POST['userID']   :  null;
$line    = (isset( $_POST['line'] )      && !empty( $_POST['line'] ))     ? $_POST['line']     :  null;
$message = (isset( $_POST['message'] )   && !empty( $_POST['message'] ))  ? $_POST['message']  :  null;
$source  = (isset( $_POST['source'] )    && !empty( $_POST['source'] ))   ? $_POST['source']   :  null;
$version = (isset( $_POST['version'] )   && !empty( $_POST['version'] ))  ? $_POST['version']  :  null;
$release = (isset( $_POST['release'] )   && !empty( $_POST['release'] ))  ? $_POST['release']  :  null;

if (is_array($_POST) && array_key_exists('fromPerson', $_POST)) {
    echo 'blah' . $_POST['fromPerson'];
}

Simple. You've two choices:

1. Check if there's ANY post data at all

//Note: This resolves as true even if all $_POST values are empty strings
if (!empty($_POST))
{
    // handle post data
    $fromPerson = '+from%3A'.$_POST['fromPerson'];
    echo $fromPerson;
}

(OR)

2. Only check if a PARTICULAR Key is available in post data

if (isset($_POST['fromPerson']) )
{
    $fromPerson = '+from%3A'.$_POST['fromPerson'];
    echo $fromPerson;
}

The proper way of checking if array key exists is function array_key_exists()

The difference is that when you have $_POST['variable'] = null it means that key exists and was send but value was null

The other option is isset() which which will check if array key exists and if it was set

The last option is to use empty() which will check if array key exists if is set and if value is not considered empty.

Examples:

$arr = [
  'a' => null,
  'b' => '',
  'c' => 1
];

array_key_exists('a', $arr); // true
isset($arr['a']); // false
empty($arr['a']); // true


array_key_exists('b', $arr); // true
isset($arr['b']); // true
empty($arr['b']); // true


array_key_exists('c', $arr); // true
isset($arr['c']); // true
empty($arr['c']); // false

Regarding your question

The proper way to check if value was send is to use array_key_exists() with check of request method

if ($_SERVER['REQUEST_METHOD'] == 'POST' && array_key_exists('fromPerson', $_POST)    
{
   // logic
}

But there are some cases depends on your logic where isset() and empty() can be good as well.


Try isset($_POST['fromPerson'])?


Everyone is saying to use isset() - which will probably work for you.

However, it's important that you understand the difference between

$_POST['x'] = NULL; and $_POST['x'] = '';

isset($_POST['x']) will return false on the first example, but will return true on the second one even though if you tried to print either one, both would return a blank value.

If your $_POST is coming from a user-inputted field/form and is left blank, I BELIEVE (I am not 100% certain on this though) that the value will be "" but NOT NULL.

Even if that assumption is incorrect (someone please correct me if I'm wrong!) the above is still good to know for future use.


Try

if (isset($_POST['fromPerson']) && $_POST['fromPerson'] != "") {
    echo "Cool";
}

  • In that case using method isset is not appropriate.

According to PHP documentation: http://php.net/manual/en/function.array-key-exists.php
(see Example #2 array_key_exists() vs isset())
The method array_key_exists is intended for checking key presence in array.

So code in the question could be changed as follow:

function fromPerson() {
   if (array_key_exists('fromPerson', $_POST) == FALSE) {
        return '';
   } else {
        return '+from%3A'.$_POST['fromPerson'];
   };
}

$newString = fromPerson();


  • Checking presence of array $_POST is not necessary because it is PHP environment global variable since version 4.1.0 (nowadays we does not meet older versions of PHP).

All the methods are actually discouraged, it's a warning in Netbeans 7.4 and it surely is a good practice not to access superglobal variables directly, use a filter instead

$fromPerson = filter_input(INPUT_POST, 'fromPerson', FILTER_DEFAULT);
if($fromPerson === NULL) { /*$fromPerson is not present*/ }
else{ /*present*/ }
var_dump($fromPerson);exit(0);

I would like to add my answer even though this thread is years old and it ranked high in Google for me.

My best method is to try:

if(sizeof($_POST) !== 0){
// Code...
}

As $_POST is an array, if the script loads and no data is present in the $_POST variable it will have an array length of 0. This can be used in an IF statement.

You may also be wondering if this throws an "undefined index" error seeing as though we're checking if $_POST is set... In fact $_POST always exists, the "undefined index" error will only appear if you try to search for a $_POST array value that doesn't exist.

$_POST always exists in itself being either empty or has array values. $_POST['value'] may not exist, thus throwing an "undefined index" error.


isset($_POST['fromPerson'])