Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a function checking if a string is empty always returns true? [closed]

People also ask

Does an empty string return true Python?

So if a string is empty, it returns False, and with not operator it will return True.

How do I check if a string is empty?

Java String isEmpty() Method The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.

What does it mean if a string is empty?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .

How do you check if a string is empty in PHP?

The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.


Simple problem actually. Change:

if (strTemp != '')

to

if ($strTemp != '')

Arguably you may also want to change it to:

if ($strTemp !== '')

since != '' will return true if you pass is numeric 0 and a few other cases due to PHP's automatic type conversion.

You should not use the built-in empty() function for this; see comments and the PHP type comparison tables.


I always use a regular expression for checking for an empty string, dating back to CGI/Perl days, and also with Javascript, so why not with PHP as well, e.g. (albeit untested)

return preg_match('/\S/', $input);

Where \S represents any non-whitespace character


PHP have a built in function called empty() the test is done by typing if(empty($string)){...} Reference php.net : php empty


In your if clause in the function, you're referring to a variable strTemp that doesn't exist. $strTemp does exist, though.

But PHP already has an empty() function available; why make your own?

if (empty($str))
    /* String is empty */
else
    /* Not empty */

From php.net:

Return Values

Returns FALSE if var has a non-empty and non-zero value.

The following things are considered to be empty:

* "" (an empty string)
* 0 (0 as an integer)
* "0" (0 as a string)
* NULL
* FALSE
* array() (an empty array)
* var $var; (a variable declared, but without a value in a class)

http://www.php.net/empty


PHP evaluates an empty string to false, so you can simply use:

if (trim($userinput['phoneNumber'])) {
  // validate the phone number
} else {
  echo "Phone number not entered<br/>";
}