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

I have a function isNotEmpty which returns true if the string is not empty and false if the string is empty. I've found out that it is not working if I pass an empty string through it.

function isNotEmpty($input) 
{
    $strTemp = $input;
    $strTemp = trim($strTemp);

    if(strTemp != '') //Also tried this "if(strlen($strTemp) > 0)"
    {
         return true;
    }

    return false;
}

The validation of the string using isNotEmpty is done:

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

If the string is empty the else doesn't execute, I don't understand why, can someone please shed some light on this please.

This question is related to php string validation

The answer is


if you have a field namely serial_number and want to check empty then

$serial_number = trim($_POST[serial_number]);
$q="select * from product where user_id='$_SESSION[id]'";
$rs=mysql_query($q);
while($row=mysql_fetch_assoc($rs)){
if(empty($_POST['irons'])){
$irons=$row['product1'];
}

in this way you can chek all the fileds in the loop with another empty function


Well here is the short method to check whether the string is empty or not.

$input; //Assuming to be the string


if(strlen($input)==0){
return false;//if the string is empty
}
else{
return true; //if the string is not empty
}

I just write my own function, is_string for type checking and strlen to check the length.

function emptyStr($str) {
    return is_string($str) && strlen($str) === 0;
}

print emptyStr('') ? "empty" : "not empty";
// empty

Here's a small test repl.it

EDIT: You can also use the trim function to test if the string is also blank.

is_string($str) && strlen(trim($str)) === 0;    

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 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/>";
}

You got an answer but in your case you can use

return empty($input);

or

return is_string($input);

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


I needed to test for an empty field in PHP and used

ctype_space($tempVariable)

which worked well for me.


this is the short and effective solution, exactly what you're looking for :

return $input > null ? 'not empty' : 'empty' ;

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


Just use strlen() function

if (strlen($s)) {
   // not empty
}

You can simply cast to bool, dont forget to handle zero.

function isEmpty(string $string): bool {
    if($string === '0') {
        return false;
    }
    return !(bool)$string;
}

var_dump(isEmpty('')); // bool(true)
var_dump(isEmpty('foo')); // bool(false)
var_dump(isEmpty('0')); // bool(false)

I know this thread been pretty old but I just wanted to share one of my function. This function below can check for empty strings, string with maximum lengths, minimum lengths, or exact length. If you want to check for empty strings, just put $min_len and $max_len as 0.

function chk_str( $input, $min_len = null, $max_len = null ){

    if ( !is_int($min_len) && $min_len !== null ) throw new Exception('chk_str(): $min_len must be an integer or a null value.');
    if ( !is_int($max_len) && $max_len !== null ) throw new Exception('chk_str(): $max_len must be an integer or a null value.'); 

    if ( $min_len !== null && $max_len !== null ){
         if ( $min_len > $max_len ) throw new Exception('chk_str(): $min_len can\'t be larger than $max_len.');
    }

    if ( !is_string( $input ) ) {
        return false;
    } else {
        $output = true;
    }

    if ( $min_len !== null ){
        if ( strlen($input) < $min_len ) $output = false;
    }

    if ( $max_len !== null ){
        if ( strlen($input) > $max_len ) $output = false;
    }

    return $output;
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery