Test for Empty String ?
Moderator: General Moderators
Test for Empty String ?
Hi guys, should I do this to test for an empty string:
if(strlen($strMyString) == 0)...
or this to avoid a function call:
if($strMyString == "")...
? The later seems more efficient but does it really test for an empty string ? Maybe there is an even better method ? Thanks.
if(strlen($strMyString) == 0)...
or this to avoid a function call:
if($strMyString == "")...
? The later seems more efficient but does it really test for an empty string ? Maybe there is an even better method ? Thanks.
- hob_goblin
- Forum Regular
- Posts: 978
- Joined: Sun Apr 28, 2002 9:53 pm
- Contact:
I've always used the latter, but I'm trying to change to the
flipped version as it seems to be gaining favor in the community and does help catch the common assignment instead of comparision bug. I can't think of a case in PHP where your two versions would give different results.
Code: Select all
if (""==$strMyString))1) that breaks with $strMyString = 0; (zero is equivalent to false (but of a different type, so === will return the correct answer) in PHP)
2) it's not generally good practice to use Hungarian Notation in PHP (the str in strMyString. it's ugly and not useful particularly in a loosely typed language)
2) it's not generally good practice to use Hungarian Notation in PHP (the str in strMyString. it's ugly and not useful particularly in a loosely typed language)
- protokol
- Forum Contributor
- Posts: 353
- Joined: Fri Jun 21, 2002 7:00 pm
- Location: Cleveland, OH
- Contact:
Code: Select all
if (strlen(trim($string)) == 0) {
echo "String is empty";
}just remember thatwill say 'is empty' because "0" is evaluated as empty
Code: Select all
<html><body>
<?php
$s = "0";
print( empty($s)? 'is empty' : 'is not empty');
?>
</body></html>Oh, thanks, I didn't realize that. So if some guy enters "0" into a form textbox and I use empty() it will equate to TRUE.
Damn, so should I just use the if($textboxString == "") to check for an empty textbox ?
Or the if(strlen($textboxString) == 0) ?
This is to verify whether or not someone entered something into a form textbox. Both methods seem to work just fine.
Thanks guys.
Damn, so should I just use the if($textboxString == "") to check for an empty textbox ?
Or the if(strlen($textboxString) == 0) ?
This is to verify whether or not someone entered something into a form textbox. Both methods seem to work just fine.
Thanks guys.