Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should i use empty() php function

Tags:

php

which is better?

if (!empty($val)) { // do something }

and

if ($val) { // do something }

when i test it with PHP 5, all cases produce the same results. what about PHP 4, or have any idea which way is better?

like image 788
duy.ly Avatar asked Aug 31 '11 16:08

duy.ly


People also ask

What is the purpose of the PHP empty () function?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.

Should I use empty or Isset?

"isset() checks if a variable has a value including (False, 0 or empty string), but not NULL. Returns TRUE if var exists; FALSE otherwise. On the other hand the empty() function checks if the variable has an empty value empty string, 0, NULL or False. Returns FALSE if var has a non-empty and non-zero value."

Is empty array true in PHP?

An empty array evaluates to FALSE , any other array to TRUE (Demo):

Is empty same as NULL PHP?

NULL and empty - PHP TutorialNull is a fancy term for nothing, for not having a value. It's not zero, it's not an empty string, it's the actual lack of a value. I mean, if we can set a value into a variable, then we also have to have some way to talk about the fact that variable might not have a value at all.


1 Answers

You should use the empty() construct when you are not sure if the variable even exists. If the variable is expected to be set, use if ($var) instead.

empty() is the equivalent of !isset($var) || $var == false. It returns true if the variable is:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)
like image 189
Arnaud Le Blanc Avatar answered Oct 30 '22 09:10

Arnaud Le Blanc