241

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.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
bgosalci
  • 2,685
  • 2
  • 17
  • 8
  • 60
    Just a suggestion: it is generally a bad practice to use functions with negated names. It is more readable to have function isEmpty($input), otherwise you might call it like this: if (!isNotEmpty($x)) ... On the other hand, isNotEmpty() and (!isEmpty()) is not that different. YMMV. – johndodo Oct 27 '11 at 08:30
  • 1
    To have the same function without a negated name, perhaps something like hasContent(). – OsakaWebbie Jun 18 '15 at 08:58
  • *!thatDifferent* @johndodo – coderatchet Mar 09 '17 at 00:47
  • This is DEFINITELY an **Off-topic: Typo** question. – mickmackusa Jun 03 '20 at 08:03

14 Answers14

340

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.

GKFX
  • 1,386
  • 1
  • 11
  • 30
cletus
  • 616,129
  • 168
  • 910
  • 942
  • 4
    Arguably, change the if into: return $strTemp !== ''; – strager Apr 05 '09 at 17:39
  • Yes, that's it, I don't know how I missed on the $ sign. Also tested passing value 0 and it works. Thanks for your response. – bgosalci Apr 05 '09 at 20:35
  • 12
    you don't want to use empty(). Consider a string of spaces: $x = " "; var_dump(!empty($x)); /* (TRUE) */ var_dump(isNotEmpty($x)); /* (FALSE) */ – nickf Apr 06 '09 at 13:15
  • 5
    The OP is trimming the string. In this case its appropriate. – cletus Apr 06 '09 at 14:00
  • 8
    @cletus: then consider a string $s='0'. If you call empty($s) it will evaluate to true (not intuitive imho, but it is so). – johndodo Oct 27 '11 at 08:26
  • 30
    Don't use empty()! empty() will return true for values such as '0'. See php.net/manual/en/types.comparisons.php – Scott Tesler Apr 23 '13 at 19:12
  • 1
    I've yet to understand why `if( $str !== '' )` is not the definitive answer for this question... I'd genuinely like to know if there's any reason for not using this always, or if there is a valid reason to jump through hoops not to use it. – mike rodent Dec 02 '17 at 09:53
  • i think the better approach is simply checking the length of the string i.e. `strlen($data)` – oldboy Jan 31 '20 at 20:26
30

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

Dexygen
  • 12,287
  • 13
  • 80
  • 147
  • 1
    This is the only solution here that doesn't assume zero is the same as an empty string! – Matthew Lock Oct 10 '15 at 01:00
  • 1
    Cool solution. As a side note, https://stackoverflow.com/a/4544642/5411817 mentions: *By default `.` doesn't match new lines - `[\s\S]` is a hack around that problem. This is common in JavaScript, but in PHP you can use the `/s` flag to to make the dot match all characters.* And https://stackoverflow.com/a/4544646/5411817 mentions: *`(?s)` turns on the `s` mode and `(?-s)` turns if off. Once turned off any following `.` will not match a newline.* if you want to turn the switch on/off inline (embedded inside the regex) instead of as a regex flag. – SherylHohman Apr 11 '20 at 23:05
24

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

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Björn
  • 29,019
  • 9
  • 65
  • 81
  • 13
    Not all implementations would want "0" to be evaluated as empty. And if he wanted that, couldn't he just as well use the if($x) comparison i.e. If(!trim($str))? – Calvin Apr 05 '09 at 16:37
  • 1
    Note that doing $tmpStr != '' will also return true of $tmpStr holds 0 or false or another empty/false value. – Pim Jager Apr 05 '09 at 17:42
  • 5
    Your version won't actually work: empty works on variables, not on expressions. – Hound Aug 07 '10 at 12:25
23

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

axel22
  • 32,045
  • 9
  • 125
  • 137
Malak
  • 579
  • 4
  • 4
13

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/>";
}
troelskn
  • 115,121
  • 27
  • 131
  • 155
  • 9
    This works fine until you pas 0. Otherwise the idea is great, I'll us it it on some other places. Thanks for your response. – bgosalci Apr 05 '09 at 20:28
10

Just use strlen() function

if (strlen($s)) {
   // not empty
}
justyy
  • 5,831
  • 4
  • 40
  • 73
  • 1
    it depends on how PHP implements strlen() function. For example, in Delphi, the string actually has stored its length minus 4 byte offset, so checking its length is trivial. – justyy Nov 05 '15 at 16:17
  • 5
    Not type save. Before `Php 5.3` the function will return `5` if `$s` is of type `array`. `Php > 5.3` will rise an exception. I recommend using `is_string($s) && str_len($s) > 0`. `>0` just for reading purposes. – magic_al Mar 10 '16 at 10:12
7

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;    
svarog
  • 9,477
  • 4
  • 61
  • 77
1

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

ctype_space($tempVariable)

which worked well for me.

Joey Phillips
  • 1,543
  • 2
  • 14
  • 22
TRayman
  • 19
  • 1
0

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
}
abhishek bagul
  • 243
  • 2
  • 16
0

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)
fabpico
  • 2,628
  • 4
  • 26
  • 43
  • `(bool)$str` is the same as doing `!empty($str)`, and has the same problem with `'0'`. Read [PHP Booleans](https://www.php.net/manual/en/language.types.boolean.php), the section "Converting to boolean". Also, you got it backwards - should be `!(bool)$string'`. Or your function should be named "isNotEmpty". Regardless, you are stuck with incorrect handling of '0'. – ToolmakerSteve Jul 01 '19 at 21:07
  • @ToolmakerSteve For the `0` problem just handle that before returning the casted string. And thanks a lot, i forgot the negation `!` (negated function names are bad practice). Edited my post. – fabpico Jul 02 '19 at 10:01
-1

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;
}
Kevin Ng
  • 2,146
  • 1
  • 13
  • 18
-2

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

user2042007
  • 35
  • 1
  • 6
-2

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

return $input > null ? 'not empty' : 'empty' ;
Moti Winkler
  • 308
  • 1
  • 4
  • 19
  • I haven't tested whether this works, but if it does, it would be by converting `null` to empty string for comparison. In which case, it would be much clearer to say what you mean: `$input > ''`. That is, "perform a lexical comparison between the input string and an empty string". Or to ignore whitespace at ends: `trim($input) > ''`. – ToolmakerSteve Jul 01 '19 at 21:27
  • ... Also need to test what happens when `$input` is `'0'`. Not clear whether php does a `numeric` or `lexical` comparison, when first argument is a numeric string. – ToolmakerSteve Jul 01 '19 at 21:34
-3

You got an answer but in your case you can use

return empty($input);

or

return is_string($input);
geekido
  • 171
  • 5
  • 5
    this fails for `empty("0")` – psiyumm Nov 28 '15 at 13:27
  • 2
    @geekido - downvoting wrong answers is part of StackOverflow - it moves those answers down, and encourages answerers to correct their answer, or remove it. Do you understand what is wrong with your answer? 1. `empty` - this answer has already been given, so saying it again doesn't contribute anything. Worse, as has been discussed in comments, it is wrong - any value equivalent to `0` will be considered "empty". 2. `is_string` is wrong in a different way - an empty string `''` is a string, so will return true in that case - fails to do what question asks. – ToolmakerSteve Jul 01 '19 at 20:51