How to check empty string values in PHP?

How to check empty string values in PHP?

As a PHP programmer most of the time you have to deal with form submission. In a form submission page, user may be submit a form without filling all required fields like user name, valid user email address or passwords. In that situation your system must show a notification message that, “user name field” is required. In another case, sometimes user submitted form with just a single white space. Generally, spammers do such type of bad activities. To protect/handle this issue, we need to check each values properly and need to make sure there is valid information in submitted form.

Solution to check empty string values in PHP?

 

we use 2 PHP functions to check empty strings. They are trim() and isset() function.

trim() function remove white spaces both side from a string. That means if user submit a form with white space then we can easily remove them by using trim function. After that if we check with a conditional expression then our system can easily return a message that, there is no valid character in your submitted string or string is null/empty. isset() function is very useful when we are not exactly sure about string variable is exist of not.  so, let’s go for the snippets-

 

//Following string contain only white space

$string = " "; 

// Now check if string is empty

echo (!isset($string) || trim($string) == "") ? "Empty" : "Not empty"

// result: "Empty"

 

Enjoy! Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!

Tags:  

Share It

Related Posts