PHP - Best Practice for Evaluating IF Expressions

Consider the following

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

Each line above pretty much does the same thing. I didn’t say much about which one I use. Should I be more specific? Does it really matter?

+3
source share
4 answers

I would use this:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // POST request
}
+9
source

I always preferred to use it empty(), since it returns True if the argument variable is either canceled or set, but evaluates to False (which will be an empty array). This saves my step and replaces the equivalent of if(!isset($_POST) || !$_POST) { echo 'something'; }the chaos just mentioned.

+1
source

, POST, $_SERVER ['request_method'] - .

, , :

  • ()

, "". PHP , :

*  "" (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)

- , , , :

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

, :

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

, count, .

  • ()

Count - "" , , . .

  • if ($ value) {// -}

count, $ , , false, , count.

, :

$var = ''; // empty string
var_dump(empty($var)); // returns true
var_dump(count($var)); // returns false
+1
source

Whatever you choose, agree with him!

0
source

Source: https://habr.com/ru/post/1705119/


All Articles