Why a function checking if a string is empty always returns true?
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.
Why is True returned when checking if an empty string is in another?
From the documentation:
For the Unicode and string types,
x in y
is true if and only if x is a substring of y. An equivalent test isy.find(x) != -1
. Note, x and y need not be the same type; consequently,u'ab' in 'abc'
will returnTrue
. Empty strings are always considered to be a substring of any other string, so"" in "abc"
will returnTrue
.
From looking at your print
call, you're using 2.x.
To go deeper, look at the bytecode:
>>> def answer():
... '' in 'lolsome'
>>> dis.dis(answer)
2 0 LOAD_CONST 1 ('')
3 LOAD_CONST 2 ('lolsome')
6 COMPARE_OP 6 (in)
9 POP_TOP
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
COMPARE_OP
is where we are doing our boolean operation and looking at the source code for in
reveals where the comparison happens:
TARGET(COMPARE_OP)
{
w = POP();
v = TOP();
if (PyInt_CheckExact(w) && PyInt_CheckExact(v)) {
/* INLINE: cmp(int, int) */
register long a, b;
register int res;
a = PyInt_AS_LONG(v);
b = PyInt_AS_LONG(w);
switch (oparg) {
case PyCmp_LT: res = a < b; break;
case PyCmp_LE: res = a <= b; break;
case PyCmp_EQ: res = a == b; break;
case PyCmp_NE: res = a != b; break;
case PyCmp_GT: res = a > b; break;
case PyCmp_GE: res = a >= b; break;
case PyCmp_IS: res = v == w; break;
case PyCmp_IS_NOT: res = v != w; break;
default: goto slow_compare;
}
x = res ? Py_True : Py_False;
Py_INCREF(x);
}
else {
slow_compare:
x = cmp_outcome(oparg, v, w);
}
Py_DECREF(v);
Py_DECREF(w);
SET_TOP(x);
if (x == NULL) break;
PREDICT(POP_JUMP_IF_FALSE);
PREDICT(POP_JUMP_IF_TRUE);
DISPATCH();
}
and where cmp_outcome is in the same file, it's easy to find our next clue:
res = PySequence_Contains(w, v);
which is in abstract.c:
{
Py_ssize_t result;
if (PyType_HasFeature(seq->ob_type, Py_TPFLAGS_HAVE_SEQUENCE_IN)) {
PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
if (sqm != NULL && sqm->sq_contains != NULL)
return (*sqm->sq_contains)(seq, ob);
}
result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
}
and to come up for air from the source, we find this next function in the documentation:
objobjproc PySequenceMethods.sq_contains
This function may be used by
PySequence_Contains()
and has the same signature. This slot may be left to NULL, in this casePySequence_Contains()
simply traverses the sequence until it finds a match.
and further down in the same documentation:
int PySequence_Contains(PyObject *o, PyObject *value)
Determine if o contains value. If an item in o is equal to value, return
1
, otherwise return0
. On error, return-1
. This is equivalent to the Python expressionvalue in o
.
Where ''
isn't null
, the sequence 'lolsome'
can be thought to contain it.
How do I check for an empty/undefined/null string in JavaScript?
Empty string, undefined, null, ...
To check for a truthy value:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
To check for a falsy value:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
Empty string (only!)
To check for exactly an empty string, compare for strict equality against ""
using the ===
operator:
if (strValue === "") {
// strValue was empty string
}
To check for not an empty string strictly, use the !==
operator:
if (strValue !== "") {
// strValue was not an empty string
}
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
You can just check if the variable has a truthy
value or not. That means
if( value ) {
}
will evaluate to true
if value
is not:
- null
- undefined
- NaN
- empty string ("")
- 0
- false
The above list represents all possible falsy
values in ECMA-/Javascript. Find it in the specification at the ToBoolean
section.
Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof
operator. For instance
if( typeof foo !== 'undefined' ) {
// foo could get resolved and it's defined
}
If you can be sure that a variable is declared at least, you should directly check if it has a truthy
value like shown above.
How to check if the string is empty?
Empty strings are "falsy" (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:
if not myString:
This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use:
if myString == "":
See the documentation on Truth Value Testing for other values that are false in Boolean contexts.
How do I check for an empty/undefined/null string in JavaScript?
Empty string, undefined, null, ...
To check for a truthy value:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
To check for a falsy value:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
Empty string (only!)
To check for exactly an empty string, compare for strict equality against ""
using the ===
operator:
if (strValue === "") {
// strValue was empty string
}
To check for not an empty string strictly, use the !==
operator:
if (strValue !== "") {
// strValue was not an empty string
}
Why does contains() method find empty string in non-empty string in Java
An empty string occurs in every string. Specifically, a contiguous subset of the string must match the empty string. Any empty subset is contiguous and any string has an empty string as such a subset.
Returns true if and only if this string contains the specified sequence of char values.
An empty set of char values exists in any string, at the beginning, end, and between characters. Out of anything, you can extract nothing. From a physical piece of string/yarn I can say that a zero-length portion exists within it.
If contains returns true there is a possible substring(
invocation to get the string to find. "aaa".substring(1,1)
should return ""
, but don't quote me on that as I don't have an IDE at the moment.
Checking if string is null or undefined always returns False
Edit:
As mentioned by Aymen TAGHLISSIA in the comments, a FormControl might be a more elegant way to implement a form and its validation. Here is an Introduction to forms in Angular and also an example using Reactive forms .
Original answer:
Rewrite your function as followed with !this.filename
:
function validate(): boolean {
if (!this.filename) {
this.error = true;
this.message = "Please enter valid filename";
return false;
}
return true;
}
console.log(validate(null)); // false
console.log(validate(undefined)); // false
console.log(validate('')); // false
console.log(validate('valid')); // true
Though you could also think about passing a string as parameter:
function validate(str: string): boolean {
// Reset error and message?
// ...
if (!str) {
this.error = true;
this.message = "Please enter non empty string";
return false;
}
// Or reset error and message here
// this.error = false;
// this.message = undefined;
return true;
}
And then something like:
if (!validate(this.filename)) {
// Valid filename
} else {
// Error
}
PHP best way to check whether a string is empty or not
Since PHP will treat a string containing a zero ('0') as empty, it makes the empty()
function an unsuitable solution.
Instead, test that the variable is explicitly not equal to an empty string:
$stringvar !== ''
As the OP and Gras Double and others have shown, the variable should also be checked for initialization to avoid a warning or error (depending on settings):
isset($stringvar)
This results in the more acceptable:
if (isset($stringvar) && $stringvar !== '') {
}
PHP has a lot of bad conventions. I originally answered this (over 9 years ago) using the empty()
function, as seen below. I've long since abandoned PHP, but since this answer attracts downvotes and comments every few years, I've updated it. Should the OP wish to change the accepted answer, please do so.
Original Answer:
if(empty($stringvar))
{
// do something
}You could also add
trim()
to eliminate whitespace if that is to be considered.Edit:
Note that for a string like '
0
', this will return true, whilestrlen()
will not.
Related Topics
Simplexml Get Attributes with a Namespace
Url Rewriting-Code for Rewriting
Show Hide Payment Methods Based on Selected Shipping Method in Woocommerce
Optimizing Kohana-Based Websites for Speed and Scalability
Leverage Browser Caching, How on Apache or .Htaccess
Which MySQL Datatype to Use for an Ip Address
Why Use Sprintf Function in PHP
In PHP What Does It Mean by a Function Being Binary-Safe
Why a Function Checking If a String Is Empty Always Returns True
Convert Datetime to String PHP
Accessing JSON Array After JSON_Decode/Multidimensional Array
Passing Variables from PHP to JavaScript
PHP Files Are Downloaded by Browser Instead of Processed by Local Dev Server (Mamp)