Why a function checking if a string is empty always returns true?
PhpStringValidationPhp Problem Overview
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.
Php Solutions
Solution 1 - Php
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.
Solution 2 - Php
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
Solution 3 - Php
PHP have a built in function called empty()
the test is done by typing
if(empty($string)){...}
Reference php.net : php empty
Solution 4 - Php
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)
Solution 5 - Php
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/>";
}
Solution 6 - Php
Just use strlen() function
if (strlen($s)) {
// not empty
}
Solution 7 - Php
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
EDIT: You can also use the trim function to test if the string is also blank.
is_string($str) && strlen(trim($str)) === 0;
Solution 8 - Php
I needed to test for an empty field in PHP and used
ctype_space($tempVariable)
which worked well for me.
Solution 9 - Php
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
}
Solution 10 - Php
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)
Solution 11 - Php
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;
}
Solution 12 - Php
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
Solution 13 - Php
this is the short and effective solution, exactly what you're looking for :
return $input > null ? 'not empty' : 'empty' ;
Solution 14 - Php
You got an answer but in your case you can use
return empty($input);
or
return is_string($input);