Reputation: 815
PHP If Statement if (!$_POST)
- What does !$_POST
mean?
For instance, in some legacy code I'm looking at, the code reads:
<form action="paypalorders.php" method="POST">
<input type="hidden" name="orderList" value="' . $orderList . '">
<input type="submit" value="Archive">
</form>';
if (!$_POST) {
file_put_contents('/orders.txt', $output_line1);
}
I've looked at a bunch of other threads and haven't seen this exact question asked, so I'm trying to find out what it is. I've seen threads that format it like this:
if(!empty($_POST)) {
But not quite the same as what I'm looking for. Is it the same thing, just shorthand? I'm not sure, which is why I'm asking. I've Googled around and looked at a handful of threads and I'm still not sure.
Thank you.
Upvotes: 5
Views: 6638
Reputation: 41810
The !
(not) logical operator returns true
if the argument on its right-hand side is not true. It forces the argument to be evaluated as a boolean. In this case, when the $_POST
array is evaluated as a boolean it will evaluate as true
if it is not empty and false
if it is. (See converting to boolean.)
if (!$_POST) {
should be a safe way to detect whether or not anything is in $_POST
if you want to do that. empty
isn't necessary in that case because superglobals are always set, and since you aren't referring to a specific key, you don't need to worry about an undefined index notice.
I think it's also worth mentioning that if the only point of the check is to see what type of request was sent, it is probably better to just check the request method directly, because !$_POST
does not mean the request wasn't a post, since a post request can be empty.
Upvotes: 5
Reputation: 27864
(bool)$array
evaluates to true
if $array
contains elements, and false
if it is empty.
Since $_POST
is an array, !$_POST
returns true
if $_POST
is empty.
Another way to interpret this, you are performing conditional tasks for the case where this page was not reached through a HTTP POST method.
Upvotes: 2
Reputation: 21473
when you cast an array to bool, it will be cast to bool(false) if the array is empty (eg if count($arr)===0), or bool(true) otherwise. !
casts whatever it's checking to bool. because $_POST always exists, if (!$_POST) {
and if(empty($_POST)) {
both do the exact same thing, they check if $_POST is empty. it's not even about being legacy code, this is still perfectly valid for 7.3.0. the difference between the 2 approaches will only become apparent when you're checking variables that may not exist
, !$arr
will trow an Notice: Undefined variable
-error if $arr doesn't exist, empty($arr)
will not.
Upvotes: 0
Reputation: 70
Since $_POST is an array, if it's empty his value is null, so if(!$_POST) would look like this:
if(!null){
//code
}
The following code returns true or false, but the objective of both is the same.
if(!empty($_POST)){
//code
}
Hope it helps you!
Upvotes: 2