PHP - Best practices evaluating IF statement

By : John
Source: Stackoverflow.com
Question!

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?

By : John


Answers

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


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.

By : yukondude


I would use this:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // POST request
}
By : Gumbo


This video can help you solving your question :)
By: admin