MrPizzaFace
MrPizzaFace

Reputation: 8086

What is a proper function to check if input is empty/blank?

I've been using the empty function to validate if a form submission is made blank. However, I just realized that empty passes " *whitespace* " as NOT empty, which is obviously not what I want.

Examples:

    $text = "is this empty?";
    if (empty($text)) {
        echo 'Yes, Empty!';
     } 
             // return is NOT empty

    $text = "         ";
    if (empty($text)) {
        echo 'Yes, Empty!';
     } 
             // return is NOT empty

Right now I am using:

    $text = "         ";
    if (!trim($text)) {
        echo 'Yes, Empty!';
     } 
             // return is Yes, Empty!

I need to understand:

  1. What is empty used for?
  2. Am I properly using trim for my purposes?
  3. Is their another function I can use specifically for my purpose?

Upvotes: 2

Views: 174

Answers (2)

Jimmie Johansson
Jimmie Johansson

Reputation: 1962

  1. Empty is used for checking if something is, well, empty. If there are spaces, it is not empty.
  2. Trim removes the spaces before the first, and after the last character of your string. If there are no characters the trim will make your string with blank spaces empty. So yes, you are using it correct here.
  3. As the previous answer said, you can use both empty and trim together if you don't want spaces to prevent your string from being empty. But the prefered way is to check if trim($string) is false.

Upvotes: 1

John Conde
John Conde

Reputation: 219824

Use both trim() and empty() together:

$text = "         ";
if (empty(trim($text))) {
    echo 'Yes, Empty!';
} 

Upvotes: 3

Related Questions