Checking for empty arrays: count vs empty
I generally use empty
. Im not sure why people would use count really - If the array is large then count takes longer/has more overhead. If you simply need to know whether or not the array is empty then use empty.
How to check whether an array is empty using PHP?
If you just need to check if there are ANY elements in the array, you can use either the array itself, due to PHP's loose typing, or - if you prefer a stricter approach - use count()
:
if (!$playerlist) {
// list is empty.
}
if (count($playerlist) === 0) {
// list is empty.
}
If you need to clean out empty values before checking (generally done to prevent explode
ing weird strings):
foreach ($playerlist as $key => $value) {
if (!strlen($value)) {
unset($playerlist[$key]);
}
}
if (!$playerlist) {
//empty array
}
How to check if an array is empty or exists?
if (typeof image_array !== 'undefined' && image_array.length > 0) {
// the array is defined and has at least one element
}
Your problem may be happening due to a mix of implicit global variables and variable hoisting. Make sure you use var
whenever declaring a variable:
<?php echo "var image_array = ".json_encode($images);?>
// add var ^^^ here
And then make sure you never accidently redeclare that variable later:
else {
...
image_array = []; // no var here
}
How to check if array is empty or does not exist?
You want to do the check for undefined
first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array does not exist or is empty
}
Update
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null
values, other types of objects with a length
property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length
property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ⇒ do not attempt to process array
}
To break it down:
Array.isArray()
, unsurprisingly, checks whether its argument is an array. This weeds out values likenull
,undefined
and anything else that is not an array.
Note that this will also eliminate array-like objects, such as thearguments
object and DOMNodeList
objects. Depending on your situation, this might not be the behavior you're after.The
array.length
condition checks whether the variable'slength
property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons likearray.length != 0
orarray.length !== 0
are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ⇒ do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ⇒ probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ⇒ do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ⇒ probably OK to process array
}
Check if optional array is empty
Updated answer for Swift 3 and above:
Swift 3 has removed the ability to compare optionals with >
and <
, so some parts of the previous answer are no longer valid.
It is still possible to compare optionals with ==
, so the most straightforward way to check if an optional array contains values is:
if array?.isEmpty == false {
print("There are objects!")
}
Other ways it can be done:
if array?.count ?? 0 > 0 {
print("There are objects!")
}
if !(array?.isEmpty ?? true) {
print("There are objects!")
}
if array != nil && !array!.isEmpty {
print("There are objects!")
}
if array != nil && array!.count > 0 {
print("There are objects!")
}
if !(array ?? []).isEmpty {
print("There are objects!")
}
if (array ?? []).count > 0 {
print("There are objects!")
}
if let array = array, array.count > 0 {
print("There are objects!")
}
if let array = array, !array.isEmpty {
print("There are objects!")
}
If you want to do something when the array is nil
or is empty, you have at least 6 choices:
Option A:
if !(array?.isEmpty == false) {
print("There are no objects")
}
Option B:
if array == nil || array!.count == 0 {
print("There are no objects")
}
Option C:
if array == nil || array!.isEmpty {
print("There are no objects")
}
Option D:
if (array ?? []).isEmpty {
print("There are no objects")
}
Option E:
if array?.isEmpty ?? true {
print("There are no objects")
}
Option F:
if (array?.count ?? 0) == 0 {
print("There are no objects")
}
Option C exactly captures how you described it in English: "I want to do something special only when it is nil or empty." I would recommend that you use this since it is easy to understand. There is nothing wrong with this, especially since it will "short circuit" and skip the check for empty if the variable is nil
.
Previous answer for Swift 2.x:
You can simply do:
if array?.count > 0 {
print("There are objects")
} else {
print("No objects")
}
As @Martin points out in the comments, it uses func ><T : _Comparable>(lhs: T?, rhs: T?) -> Bool
which means that the compiler wraps 0
as an Int?
so that the comparison can be made with the left hand side which is an Int?
because of the optional chaining call.
In a similar way, you could do:
if array?.isEmpty == false {
print("There are objects")
} else {
print("No objects")
}
Note: You have to explicitly compare with false
here for this to work.
If you want to do something when the array is nil
or is empty, you have at least 7 choices:
Option A:
if !(array?.count > 0) {
print("There are no objects")
}
Option B:
if !(array?.isEmpty == false) {
print("There are no objects")
}
Option C:
if array == nil || array!.count == 0 {
print("There are no objects")
}
Option D:
if array == nil || array!.isEmpty {
print("There are no objects")
}
Option E:
if (array ?? []).isEmpty {
print("There are no objects")
}
Option F:
if array?.isEmpty ?? true {
print("There are no objects")
}
Option G:
if (array?.count ?? 0) == 0 {
print("There are no objects")
}
Option D exactly captures how you described it in English: "I want to do something special only when it is nil or empty." I would recommend that you use this since it is easy to understand. There is nothing wrong with this, especially since it will "short circuit" and skip the check for empty if the variable is nil
.
Check if array is empty or includes the value, typescript
Acctually, array is a reference type
. When you would like to check it with [ ]
, they aren't equal. They're totally different, it's better to check this condition with length
. So based on your code you should do something like this :
if (!testArray || testArray.length == 0 || testArray.includes(value)) {
// do something
}
Check whether an array is empty
There are two elements in array and this definitely doesn't mean that array is empty. As a quick workaround you can do following:
$errors = array_filter($errors);
if (!empty($errors)) {
}
array_filter()
function's default behavior will remove all values from array which are equal to null
, 0
, ''
or false
.
Otherwise in your particular case empty()
construct will always return true
if there is at least one element even with "empty" value.
Related Topics
When to Generate a New Application Key in Laravel
Htaccess Access to File by Ip Range
Object-Oriented-Like Structures in Relational Databases
Lsa - Latent Semantic Analysis - How to Code It in PHP
The Correct Way to Delete All Files Older Than 2 Days in PHP
Check If String Is Just White Space
How to Trigger Xdebug Profiler for a Command Line PHP Script
Advantages/Inconveniences of Heredoc VS Nowdoc in PHP
How to Implement "Maintenance Mode" on Already Established Website