Checking if a string is empty? |
I've seen a number of times where people check if the string is empty even if there is no empty string. For example checking if a username string is present in a session cookie.
Ive seen people do this: Code: if($this->session->userdata('username')=="") Which will work because PHP is a loosely typed language. But the problem is that there is no empty string (unless you specifically insert an empty string), if you havent inserted anything the value will be NULL. NULL and empty string are different entities. So if you check against the type too e.g. if($this->session->userdata('username')==="") then the code will fail. The better and shorter way is to do something like this - if($this->session->userdata('username')) - Because it returns TRUE if it exists and FALSE otherwise. Or if you want to reverse the logic then - if(!$this->session->userdata('username'))
Do the one thing you think you cannot do. Fail at it. Try again. Do better the second time. The only people who never tumble are those who never mount the high wire.
|
Messages In This Thread |
Checking if a string is empty? - by lexxtoronto - 04-22-2015, 08:24 AM
RE: Checking if a string is empty? - by Narf - 04-22-2015, 08:37 AM
RE: Checking if a string is empty? - by Rufnex - 04-22-2015, 08:50 AM
RE: Checking if a string is empty? - by lexxtoronto - 04-22-2015, 09:57 AM
RE: Checking if a string is empty? - by ivantcholakov - 04-22-2015, 10:42 AM
RE: Checking if a string is empty? - by lexxtoronto - 04-22-2015, 10:56 AM
RE: Checking if a string is empty? - by cartalot - 04-22-2015, 02:12 PM
RE: Checking if a string is empty? - by lexxtoronto - 04-22-2015, 03:34 PM
RE: Checking if a string is empty? - by cartalot - 04-23-2015, 03:54 PM
RE: Checking if a string is empty? - by lexxtoronto - 04-23-2015, 04:39 PM
|