How to determine if an array has any elements or not?
You can use the count()
or sizeof()
PHP functions:
if (sizeof($result) > 0) {
echo "array size is greater than zero";
}
else {
echo "array size is zero";
}
Or you can use:
if (count($result) > 0) {
echo "array size is greater than zero";
}
else {
echo "array size is zero";
}
Check if an element is present in an array
ECMAScript 2016 incorporates an includes()
method for arrays that specifically solves the problem, and so is now the preferred method.
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(1, 2); // false (second parameter is the index position in this array at which to begin searching)
As of JULY 2018, this has been implemented in almost all major browsers, if you need to support an older browser a polyfill is available.
Edit: Note that this returns false if the item in the array is an object. This is because similar objects are two different objects in JavaScript.
How do I check if an array includes a value in JavaScript?
Modern browsers have Array#includes
, which does exactly that and is widely supported by everyone except IE:
console.log(['joe', 'jane', 'mary'].includes('jane')); //true
Determine whether an array contains a value
var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};
You can use it like this:
var myArray = [0,1,2],
needle = 1,
index = contains.call(myArray, needle); // true
CodePen validation/usage
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 the array has empty element or not
As of ES2016, you should use Array.prototype.includes:
const array = ["a", "b", , "d"];
array.includes(undefined); // true
(You don't need to write undefined
, but this makes it more clear what's happening.)
Note that this method treats slots valued undefined
and empty slots the same, although they're not. If you need to differentiate these two cases as well, starting from ES2017, you can use Object.values making the following expression true
if there are empty slots in the array:
Object.values(array).length !== array.length; // true
Check if a string contains any element of an array in JavaScript
Problem lies in the for loop, which only iterates once since return ends the function, cutting off the for loop in the process. So, you can update the code like so to make the function only return once the for loop has been completed .
var arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];
function checker(value) { var prohibited = ['banana', 'apple'];
for (var i = 0; i < prohibited.length; i++) { if (value.indexOf(prohibited[i]) > -1) { return false; } } return true;}
arr = arr.filter(checker);console.log(arr);
Related Topics
Alternative for $_Server['Http_Referer'] PHP Variable in Msie
How to Determine If a PHP File Is Loaded via Cron/Command Line
Implementing "Update If Exists" in Doctrine Orm
Woocommerce New Order Action - Get Order Information
Ftp Upload File to Distant Server with Curl and PHP Uploads a Blank File
Creating a Secure File Hosting Server for PDFs
Get All Work Days in a Week for a Given Date
Codeigniter Activerecord: Join Backticking
How to Set Document Root to Be a Subdirectory Using .Htaccess and Not Vhost
Get Request from PHP Using File_Get_Contents with Parameters
Why Ob_Start() Must Come Ahead of Session_Start() to Work in PHP
How to Grab All Variables in a Post (Php)
How to Fix Server Status Code: 302 Found by SQL Inject Me Firefox Addon
How to Add More Custom Field in Linked Product of Woocommerce
Php: 'Or' Statement on Instruction Fail: How to Throw a New Exception