Page 1 of 1
Test for Empty String ?
Posted: Fri Aug 23, 2002 3:32 pm
by HUWUWA
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.
Posted: Fri Aug 23, 2002 3:36 pm
by hob_goblin
Posted: Fri Aug 23, 2002 3:36 pm
by nielsene
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.
Posted: Fri Aug 23, 2002 4:28 pm
by theChosen
What about
if (!$strMyString) echo '$strMyString is empty';
Posted: Fri Aug 23, 2002 7:08 pm
by llimllib
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)
Posted: Fri Aug 23, 2002 7:42 pm
by volka
I disagree with 2) - not completely
but sometimes it's quite useful i.e. interfacing if you want to make clear how you will treat a parameter
Posted: Fri Aug 23, 2002 11:31 pm
by protokol
Code: Select all
if (strlen(trim($string)) == 0) {
echo "String is empty";
}
Posted: Sat Aug 24, 2002 9:15 am
by HUWUWA
I'm just gonna use the empty() function; it seems the safest and most reliable. Thanks guys.
Posted: Sat Aug 24, 2002 9:19 am
by volka
just remember that
Code: Select all
<html><body>
<?php
$s = "0";
print( empty($s)? 'is empty' : 'is not empty');
?>
</body></html>
will say 'is empty' because "0" is evaluated as
empty
Posted: Sat Aug 24, 2002 9:27 am
by HUWUWA
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.
Posted: Sat Aug 24, 2002 9:28 am
by volka
I like protokol's strlen(trim()) combination
Posted: Sat Aug 24, 2002 2:46 pm
by Takuma
Looks like volka is the best...
Posted: Sat Aug 24, 2002 2:58 pm
by volka
I have to compensate the times when I talk/write complete nonsense
