120

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!

15 Answers 15

200
if( isset($_POST['fromPerson']) )
{
     $fromPerson = '+from%3A'.$_POST['fromPerson'];
     echo $fromPerson;
}
1
  • i tried this but didn't work, rather use if($_POST['fromPerson'])
    – mhdi
    Jan 3, 2022 at 16:26
75

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;
}
1
  • 1
    As per Shi's comment on Augustus Francis's answer, empty() is not correct for choice #1, because in php, the string '0' is equivalent to false - and empty() returns true for all values equivalent to false. So using empty, the code would skip printing if the value was '0'. If you want to exclude the empty string, see Augustus answer. Jan 8, 2017 at 2:38
39

Surprised it has not been mentioned

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['fromPerson'])){
6
  • 2
    Why? If server method isn't POST, then the POST variable won't be set, so the second half is all that is needed. Am I wrong? Nov 4, 2015 at 17:04
  • 2
    @ToolmakerSteve yes in most cases that is enough but not always my answer was to show another way it could be done. Dec 13, 2015 at 10:11
  • It will also work if you have a form with checkboxes and submit without a name. Mar 6, 2016 at 20:56
  • 2
    Describe a situation where isset($_POST['fromPerson'] is true, even though if($_SERVER['REQUEST_METHOD'] == 'POST' is false. Unless there is such a situation, all that is needed is the isset... part. Jan 8, 2017 at 2:13
  • True, but it's the other way around. fromPerson might not be present, but POST might still exist. The question was, "If $_POST exists." and only in an example, $_POST['fromPerson'] is used. In some situations, as @goat describes here, even if fromPerson was a Submit name, it might not be present in POST.
    – papo
    Feb 10, 2019 at 13:30
35

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.

3
  • 4
    empty() checks for variable existence and a non-empty value, so that's the function to use when an empty string should return false.
    – Han Dijk
    Jul 30, 2013 at 13:11
  • 1
    @HanDijk - as per Shi's comment on Augustus Francis's answer, empty() is not correct here, because in php, the string '0' is equivalent to false - and empty() returns true for all values equivalent to false. So using empty, the code would skip printing if the value was '0'. Jan 8, 2017 at 2:23
  • imho it's always better to write a class that would acceppt all POST data and then check inside that class. you might try to strlen on each post field and catch the exception that would result when testing against NULL, and when strlen is actually 0, it's probably because the param was ""
    – clockw0rk
    Dec 6, 2022 at 13:11
22
isset($_POST['fromPerson']) 
0
17

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.

1
  • 1
    Fantastic answer, except for the suggestion to use empty. As per Shi's comment on Augustus Francis's answer, empty() is not correct as an alternative choice, because in php, the string '0' is equivalent to false - and empty() returns true for all values equivalent to false. So using empty, the code would skip printing if the value was '0'. If you want to exclude the empty string, see Augustus answer. Jan 8, 2017 at 2:45
9
  • 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).
1
  • This code only differs in behavior from the isset solution when the post field is set but contains NULL. This is a good alternative, if you want to allow NULL in the else branch. However, it is a mistake, if a string is needed; in that situation isset does the right thing, but this code does not - it will pass the NULL value on. Robert's later answer demonstrates the difference. Jan 8, 2017 at 3:03
7

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);
4
  • 1
    On the other hand, READABILITY of code is also important. IMHO, isset is a lot more readable than a filter expression. But thank you for pointing this out; it is a useful option to consider. Nov 4, 2015 at 17:13
  • well, you can write your own myIsset/2 wrapper metod that uses filters but has the behaviour of isset/2
    – linuxatico
    Nov 5, 2015 at 8:28
  • "All the methods are actually discouraged" - that's a strong statement (even if NetBeans does mark as a warning). Do you have a link to an authoritative source, that discourages direct references to $_POST? (There is a lot about php that is designed for coding convenience rather than rigor - look at how many people in the answers to this question incorrectly use empty, tripped up by php's loose typing; its hard to imagine that accessing $_POST would be considered poor style.) Jan 8, 2017 at 2:55
  • if you only need to know if it exists but you don't care about the value, for example, to check a submit button, you can use filter_has_var(INPUT_POST, 'fromPerson').
    – PhoneixS
    Mar 31, 2022 at 14:47
5

Try

if (isset($_POST['fromPerson']) && $_POST['fromPerson'] != "") {
    echo "Cool";
}
3
  • Per Han Dijk's comment on Rafael's answer, empty($_POST['fromPerson']) does this combined test. Easier to read and to type :) Nov 4, 2015 at 17:19
  • @ToolmakerSteve: empty('0') returns true. So it's not the same.
    – Shi
    Jan 8, 2017 at 1:53
  • 1
    @Shi - yes, you are correct; what I said is wrong! It seems there is no simpler solution than the code shown here. Jan 8, 2017 at 2:19
4

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.

3

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

3
if (is_array($_POST) && array_key_exists('fromPerson', $_POST)) {
    echo 'blah' . $_POST['fromPerson'];
}
2
  • 1
    Does is_array($_POST) check if there are any values at all in POST? In my app I'm trying to determine if there was a post or not before doing anything else.
    – Jeff LaFay
    Feb 9, 2011 at 2:49
  • 1
    See my edit. is_array() checks whether it's an array, the second part checks whether it has an item with the key 'fromPerson'.
    – jezmck
    Feb 10, 2011 at 9:07
2

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

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

1
  • 2
    This answer adds nothing to the discussion, that wasn't already said in other answers, years earlier. Jan 8, 2017 at 2:34
2

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;
1
  • 5
    empty('0') is true. So better not have version 0, or userID 0, etc.
    – Shi
    Jan 8, 2017 at 1:55
-3

I recently came up with this:

class ParameterFetcher
{
public function fetchDate(string $pDate):string{
    $myVar = "";
    try{
        if(strlen($_POST[$pDate]) > 0){
            $myVar = $_POST[$pDate];
        }
    }catch (Exception $faild){
        die("field NULL or not set for $pDate");
    }

    [ ... other stuff ]

to fetch a date obviously, but it can take ANY post param. You can also check for GET this way.

6
  • Why is this a class? Why are you unsafely accessing an array index without isset check? Why would this raise an exception? Why are you testing $_POST but are getting $_GET? Why are you dieing when catching the exception? This is like… all the worst possible practices rolled into one short snippet.
    – deceze
    Dec 6, 2022 at 13:26
  • i already corrected the mistake. was posting an old version lol and the die("text") is just for debugging here. replace it with a return or standart value (or an exception object)
    – clockw0rk
    Dec 6, 2022 at 13:29
  • That still leaves a lot of unaddressed criticism…
    – deceze
    Dec 6, 2022 at 13:32
  • let me try and answere them: this is a class to keep hexagonal architecture and have a class whose domain is parsing of POST. i am unsafely accessing a post field with strlen to both check wheter it's set and if it holds a value. isset will just do about the same internally i guess
    – clockw0rk
    Dec 6, 2022 at 13:35
  • But this will produce a notice and/or warning, which is what isset is there to prevent…
    – deceze
    Dec 6, 2022 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.