views:

453

answers:

4

Consider the following

if(!count($_POST)) { echo 'something'; }
if(empty($_POST)) { echo 'something'; }
if(!$_POST) { echo 'something'; }

Each line above pretty much do the same thing. I haven't been particular about which one I use. Should I be more particular? Does it really matter?

A: 

Whatever you pick, be consistent with it!

John Rasch
+8  A: 

I would use this:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // POST request
}
Gumbo
That's what I use! And I also check to make sure my forms/arguments are there and safe as well.
Joe Philllips
Oh, and I think the "correct" way would be to have 'post' lowercase (as if it really matters).
Joe Philllips
The correct way for POST in $_SERVER['REQUEST_METHOD'] is 'POST' (upper case), just as it is upper case in the HTTP header.
Jacco
@d03boy: HTTP request method strings are case-sensitive and are always uppercase. Lowercase 'post' will not (or should not) work.
David Zaslavsky
+1  A: 

I've always preferred using empty() since it returns True if the argument variable is either unset or set but evaluates to False (which an empty array will). That saves a step in my mind and replaces the equivalent if(!isset($_POST) || !$_POST) { echo 'something'; } that chaos just mentioned.

yukondude
+1  A: 

If you want to test if the request was made using a POST request, then checking $_SERVER['request_method'] is the way to go.

If you want to find out if an array is empty, there are some differences:

  • empty()

Empty will check if a variable is "empty". PHP considers the following values to be empty:

*  "" (an empty string)
* 0 (0 as an integer)
* "0" (0 as a string)
* NULL
* FALSE
* array() (an empty array)
* var $var; (a variable declared, but without a value in a class)

Empty is a language construct, which means you can't use it as a callback, so the following will fail:

$var = array(); call_user_func('empty', $var);

It also only checks variables, so the following will fail with a fatal too:

if (empty(array()) { // do something }

It is also faster than count, but this shouldn't make you consider it over the others.

  • count()

Count is a "normal" function, it will first cast the parameter to an array, and check if it is empty. Personally I would use this to check empty arrays.

  • if ($value) { // do something }

This differs a little from count, because $value here will be cast to a boolean, and because empty arrays cast to false, it will achieve the same result as count.

There is a very big gotcha involved because of casting:

$var = ''; // empty string
var_dump(empty($var)); // returns true
var_dump(count($var)); // returns false
WishCow