PHP: if (!$val) VS if (empty($val)). Is there any difference? - php

I was wondering what's the difference the two cases below, and which one is recommended?
$val = 0;
if (!$val) {
//True
}
if (empty($val) {
//It's also True
}

Have a look at the PHP type comparison table.
If you check the table, you'll notice that for all cases, empty($x) is the same as !$x. So it comes down to handling uninitialised variables. !$x creates an E_NOTICE, whereas empty($x) does not.

If you use empty and the variable was never set/created, no warning/error will be thrown.

Let see:
empty documentation:
The following things are considered to be empty:
"" (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)
Booleans documentation:
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
It seems the only difference (regarding the resulting value) is how a SimpleXML instance is handled. Everything else seems to give the same result (if you invert the boolean cast of course).

Related

Can a class implement some logic for when it's checked by empty()?

I have a class that contains a bunch of averages, but if there is no data all the fields will be NULL, and in the eyes of my logic, "empty". However, wrapping my class in if(empty($myClassInstance)) returns false, which is correct, but I was wondering if there is any magic methods in PHP where I could say "If this objected is checked for being empty, do some stuff and return a bool"?
I realise I can add a isEmpty() method, I am just curious if this is something that can be done.
No.
From the manual:
The following things are considered to be empty:
"" (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; (a variable declared, but without a value)

if statement and functions

I sometimes see code that looks like this:
if(!Somefunction()){
// ...
}else{
// ...
}
I am more of a java developer and the only way I know the above statement holds is if the function returns a true or false at the end.
Does every function that is used in this format have to return a true or false? Or does this mean if the function is successfully executed?
No, not necessarily True or False. In PHP any variable can be converted to boolean.
When converting to boolean, the following values are considered False:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags

what is the difference between empty() and $_POST["name"]==""; in php?

i couldn't figured it out what is the real difference functionality between empty() and $_POST["xxx"]==""?
empty() is a statement (unlike any function you could define) which will not trigger an E_NOTICE if called on a variable that is actually undefined. So it also include an isset check.
Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.
Note that "equals FALSE" means an == comparison, so e.g. empty strings, a string containing a single zero, NULL, empty arrays are all considered empty.
The following things are considered to be empty (return true):
"" (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; (a variable declared, but without a value)
BUT
$_POST["xxx"]==""
Return true when $_POST["xxx"] is an empty string

if (!empty($thing)) vs if($thing)

Are these two statements executed identically, given $thing could be of any type?
if (!empty($thing)) {
// do stuff
}
if ($thing) {
// do stuff
}
I'm aware I could try it, but I'm not sure I'd catch all the edge cases... I'm afraid in some situations they would execute identically, but not all.
If $thing is undefined, then if ($thing) would throw a (non-fatal) error while if (!empty($thing)) would return false.
See empty() in the PHP documentation.
The relevant manual pages are Converting to boolean and, of course, empty(). For empty() we have this:
A variable is considered empty if it does not exist or if its value equals FALSE
So they're fully equivalent except in the situation where a variable does not exist. And in that case:
var_dump( empty($not_exists), (bool)$not_exists );
... we get:
bool(true)
bool(false)
... (among the corresponding notice) because:
the following values are considered FALSE: [...] unset variables
if (empty($foo)) is the negative of if ($foo), which can easily be seen in the type comparison tables, which means that on the lowest level:
if (!empty($foo))
is logically the same as
if ($foo)
However, for undefined variables, or array indices, if ($foo) and if ($foo['bar']) will cause an E_WARNING to occur, while if (!empty($foo)) and if (!empty($foo['bar'])) will not.
To that effect, you should prefer empty and !empty in cases where the variable or index might not exist, such as with $_GET or $_POST. In cases where the variable or index should exist, you should prefer $var and !$var specifically so that the warnings thrown are tracked, as they would likely be due to bugs.
There are some differences according to the manual, for example:
$object = new stdclass;
if ($object) {} // false in PHP 4, true in PHP 5+
Also, you can only pass variables to empty, this will throw an error:
if (empty(time()) {}
// Fatal error: Can't use function return value in write context
if (time()) {} // OK
And of course, if ($var) on an uninitialized variables will produce a notice.
if ($var) is an implicit boolean conversion. See the manual for details.
http://php.net/manual/en/language.types.boolean.php
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).
Compare to empty
http://php.net/manual/en/function.empty.php
The following things are considered to be empty:
"" (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; (a variable declared, but without a value)
So they are basically the same but with a couple very subtle differences. Use both with caution, and do type checking when possible.
empty can blow up horribly in certain cases, the biggest of which is 0 values
php > $x = 0;
php > var_dump(empty($x));
bool(true)
php > $x = false;
php > var_dump(empty($x));
bool(true);
as long as you're not requiring 0/false values to pass through, then empty() works out great.

Is There A Difference Between strlen()==0 and empty()?

I was looking at some form validation code someone else had written and I saw this:
strlen() == 0
When testing to see if a form variable is empty I use the empty() function. Is one way better than the other? Are they functionally equivalent?
There are a couple cases where they will have different behaviour:
empty('0'); // returns true,
strlen('0'); // returns 1.
empty(array()); // returns true,
strlen(array()); // returns null with a Warning in PHP>=5.3 OR 5 with a Notice in PHP<5.3.
empty(0); // returns true,
strlen(0); // returns 1.
strlen is to get the number of characters in a string while empty is used to test if a variable is empty
Meaning of empty:
empty("") //is empty for string
empty(0) // is empty for numeric types
empty(null) //is empty
empty(false) //is empty for boolean
The following things are considered to be empty:
"" (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)
strlen() simply check if the the string len is 0. It does not check for int, float etc. What is your situation.
reference
empty() will return true if $x = "0". So there is a difference.
http://docs.php.net/manual/en/types.comparisons.php
$f = 0; echo empty($f)? 'Empty':'Full'; // empty
$f = 0; echo strlen($f); // 1
For forms I use isset. It's more explicit. ;-)
empty is the opposite of boolean false.
empty is a language construct.
strlen is a function.
strlen returns the length of bytes of a string.
strlen($str)==0 is a comparison of the byte-length being 0 (loose comparison).
That comparison will result to true in case the string is empty - as would the expression of empty($str) do in case of an empty (zero-length) string, too.
However for everything else:
empty is the opposite of boolean false.
strlen returns the length of bytes of a string.
They don't share much with each other.
The strlen way is almost perfect if you want to check if something is "empty as string", that is, when a single zero should NOT be counted as nothing but empty strings, empty arrays, null and false should all be considered no value. This is quite frequently needed.
So my recommendation would be:
count($x)*strlen("$x")
This gives you:
0 for false
0 for null
0 for "" (empty string)
0 for [ ] (empty array), no warning
1 for a numeric zero
1 for "0" (a string zero)
Surely you can do empty($x) && "$x"!=="0" - it's more to the point but a little noisier, and surprisingly their time cost is nearly equal (under 50ms for a million iterations) so no reason to choose one over the other. Also, if you add !! (boolean cast) before strlen, you'll get a clear 0/1 answer for the question and sometimes it can be more convenient than true/false (debugging situations, switch, etc).
Also note that objects can't be checked like this. If there's a chance that an object comes along, go for the empty()-method. Objects are stubborn creatures.
empty() is for all variables types. strlen(), I think, is better to use with strings or something that can be safely casted to strings. For examle,
strlen(array());
will throw PHP Warning: strlen() expects parameter 1 to be string, array given error
when the input is 0,
strlen(0) = 1
empty(0) = false <-- non-empty

Categories