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!

share|improve this question

13 Answers 13

up vote 117 down vote accepted
if( isset($_POST['fromPerson']) )
{
     $fromPerson = '+from%3A'.$_POST['fromPerson'];
     echo $fromPerson;
}
share|improve this answer

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;
}
share|improve this answer
    
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. – ToolmakerSteve Jan 8 '17 at 2:38

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.

share|improve this answer
    
this also helped! thanks – eliwedel Aug 16 '10 at 23:19
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 '13 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'. – ToolmakerSteve Jan 8 '17 at 2:23

Surprised it has not been mentioned

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['fromPerson'])){
share|improve this answer
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? – ToolmakerSteve Nov 4 '15 at 17:04
    
@ToolmakerSteve yes in most cases that is enough but not always my answer was to show another way it could be done. – John Magnolia Dec 13 '15 at 10:11
    
It will also work if you have a form with checkboxes and submit without a name. – John Magnolia Mar 6 '16 at 20:56
1  
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. – ToolmakerSteve Jan 8 '17 at 2:13
isset($_POST['fromPerson']) 
share|improve this answer
  • 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).
share|improve this answer
    
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. – ToolmakerSteve Jan 8 '17 at 3:03

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.

share|improve this answer
    
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. – ToolmakerSteve Jan 8 '17 at 2:45

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);
share|improve this answer
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. – ToolmakerSteve Nov 4 '15 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 '15 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.) – ToolmakerSteve Jan 8 '17 at 2:55

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

share|improve this answer
if (is_array($_POST) && array_key_exists('fromPerson', $_POST)) {
    echo 'blah' . $_POST['fromPerson'];
}
share|improve this answer
    
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. – jlafay Feb 9 '11 at 2:49
    
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 '11 at 9:07

Try

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

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

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

share|improve this answer
    
This answer adds nothing to the discussion, that wasn't already said in other answers, years earlier. – ToolmakerSteve Jan 8 '17 at 2:34

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;
share|improve this answer
2  
empty('0') is true. So better not have version 0, or userID 0, etc. – Shi Jan 8 '17 at 1:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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