PHP in_array equivalent for Javascript
Lately I have been doing a lot work with passing data back and forth between Javascript and PHP and I often am working on arrays on the Javascript side and there is no easy native method to test whether an array contains a certain value. So I wrote my own.
function in_array(needle, haystack, strict) {
for(var i = 0; i < haystack.length; i++) {
if(strict) {
if(haystack[i] === needle) {
return true;
}
} else {
if(haystack[i] == needle) {
return true;
}
}
}
return false;
}
You could also prototype it to be built in to the native Array object. You just have to tweak the code a little.
function in_array(needle, strict) {
for(var i = 0; i < this.length; i++) {
if(strict) {
if(this[i] === needle) {
return true;
}
} else {
if(this[i] == needle) {
return true;
}
}
}
return false;
}
Array.prototype.in_array = in_array;
// example usage
var test = new Array();
test.push('i');
test.push(1);
test.in_array('i'); // true
test.in_array('i', true); // true
test.in_array('b'); // false
test.in_array(1, true); // true
test.in_array('1', true); // false

