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

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

Related

what does ($variable) return?

just doing some validation and wanted to learn really what this meant instead of it just working.
Lets say i have:
$email = $_POST['email'];
if(!$email) {
echo 'email empty'
}
Whats is just having the variable and no check for it = something mean?
I thought
$variable
by its self meant that it returned that variable as true.
So i am also using if
!$variable
is means false.
Just wanted to clear up the actual meaning behind just using the variable itself.
Is it also bad practice to compare the variable for being empty?
So is it better to use
$email == ''
Than
!$email
Sorry if its a small question without a real answer to be solved, just like to 100% understand how what i am coding actually works.
PHP evaluates if $email is "truthy" using the rules defined at http://www.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
PS $email= '' will assign '' to $email.
$email = '' will empty the variable. You can use == or === instead.
In this case, it's better to use PHP's isset() function (documentation). The function is testing whether a variable is set and not NULL.
When you do if(<expression>), it evaluates <expression>, then converts it to a boolean.
In the docs, it says:
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).
So, when you do if(!$email), it converts $email to a boolean following the above rules, then inverts that boolean.

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.

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

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).

What precautions should I take when using '0' in PHP as a number?

In PHP 0 is treated as boolean false. Hence, whenever I'm in a situation where a function has to return a numerical value and I have it return 0, or when I have a MySQL bool column with possible values of 0/1, and I use code such as this:
$active=(isActive()) ? 1 : 0;
$this->db->set('isActive',$active);
I get a feeling in the back of my mind that the 0 might be converted to null or an empty string e.g "".
What precautions do I need to take in order to have 0 always treated as an integar and not anything else?
If you want PHP to evaluate a statement with 'false' being the only 'false', use === instead of the usual ==
PHP does allow you to cast variables to a certain type.
<?php
$value = (bool) 0;
$value3 = (int) 3;
?>
If you always want 0 to be treated as a int, cast it as one.
There are a few places where 0 and '0' are treated a little bit specially. This is almost always because of automatic type co-ercion. You've already noticed where 0 evaluates to false. So if PHP has a reason to convert '0' to an integer, then that will also evaluate to false. The prime one to watch out for is the empty() function. This is documented, BTW.
I rarely use empty() because of this very problem, in fact. It makes much more sense to check more narrowly, hence I use isset(), is_null() and === false or even == 0 (or != 0). There are other checks, too. I have DB handler code that not only checks using is_null() but also does is_numeric().
Other places to watch out for are where you use other developer's code who aren't completely careful with how 0 works in automatic type co-ercion. If you give a function a 0 but it ends up using a null when it should be using a 0 then you've probably found a bug in the API and should raise it with the developer. In fact, they're probably using empty() when they should be using isset() and/or is_null(). :-)
None. 0 is 0, even if logical evaluations consider it a false value, that doesn't change its actual value.
I can't find of a single case where PHP would convert 0 to null or "". If it has to convert it to a string, it will be "0", to a boolean it will be false. There's no "null" type, so really your 0 is safe with PHP. false is converted to "" (an empty string) when cast as a string, but integers are safe.
Now it's not a guarantee that third-party code won't behave strangely when passed an integer when they expected something else, but you're mostly safe.
If you set a variable to 0, the variable remains as 0 unless you cast it to something else. The type is still integer.
You can check whether a variable is by using the is_numeric() function.
Example:
$active=(isActive()) ? 1 : 0;
if(is_numeric($active)){
$this->db->set('isActive',$active);
}
Or You can use the comparison operator === instead of the usual ==. it'll compare the data type as well as the content of the variable.
$active=(isActive()) ? 1 : 0;
if($active === 0 || $active === 1){
$this->db->set('isActive',$active);
}
Hope this helps!
Using the === comparison operator is best as it checks that the types are equal as well as their values. In php if you do:
Your best bet is to use true and false where you can, rather than setting 1 and 0 for flags. In your example, do:
$active=(isActive()) ? true : false;
or even better (assuming isActive returns a proper boolean):
$this->db->set('isActive',isActive());
rather than:
$active=(isActive()) ? 1 : 0;

How does php cast boolean variables?

How does php cast boolean variables?
I was trying to save a boolean value to an array:
$result["Users"]["is_login"] = true;
but when I use debug the is_login value is blank.
and when I do conditionals like:
if($result["Users"]["is_login"])
the conditions are always false.
Then i tried doing this:
$result["Users"]["is_login"] = "true";
and it worked.
It's not much of a big deal but when I'm returning boolean values from functions i still have to convert them to strings.
there is no cast
the
if($result["Users"]["is_login"])
should work.
can you try to use var_dump($result["Users"]["is_login"]); to make sure the variable has been set properly.
you can check is a variable is set or not by using the isset (manual) function.
Also you can find here how PHP evaluate the booleans:
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).
No casting happens in your example.
Your problem is likely somewhere else.
Would you mind to share a more complete piece of code?
Try:
if((bool)$result["Users"]["is_login"] == true)
{
// do something
}
.
And reply to one of your encounter:
but when I use debug the is_login value is blank. and when I do conditionals like:
if($result["Users"]["is_login"])
since your return value is boolean value true, in PHP it doesn't have a representation for it, therefore appear as empty (mainwhile, if the value is a boolean false, then you'll see a 0

Categories