Equivalent of PHP’s in_array() function
Posted on September 13, 2008, Filled under JavaScript,
Bookmark it
Thanks for visiting our website! We regularly publish posts like this one. If you are interested in receiving the latest updates as soon as they are posted, please consider subscribing to the RSS feed or to our e-mail newsletter.
Hello coders,
This is a JavaScript function that works like in_array() in PHP. Below is the function with a usage example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Equivalent of PHP in_array() | JavaScript Library</TITLE>
<META NAME="Author" CONTENT="Bit Repository">
<META NAME="Keywords" CONTENT="in_array, php, javascript">
<META NAME="Description" CONTENT="Equivalent of PHP in_array() | JavaScript Library">
<SCRIPT LANGUAGE="JavaScript">
function in_array(string, array)
{
for (i = 0; i < array.length; i++)
{
if(array[i] == string)
{
return true;
}
}
return false;
}
var extensions = new Array("jpg","jpeg","gif","png","bmp");
/*
// Alternative way of creating the array
var extensions = new Array();
extensions[1] = "jpg";
extensions[0] = "jpeg";
extensions[2] = "gif";
extensions[3] = "png";
extensions[4] = "bmp";
*/
var str_to_check = "bmp";
if(in_array(str_to_check, extensions))
{
alert(str_to_check +" is in our array.");
}
else
{
alert(str_to_check +" is not in our array.");
}
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
If you have any comments or suggestions regarding this script please post them.
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- September 13, 2008
- article by Gabriel C.
- 4 comments
Sponsors
Related Posts
-
Equivalent of PHP’s array_combine() functionat October 15, 2008
-
PHP: Equivalent of trim() Function for Arraysat October 5, 2008 with 2 comments
-
Validating an image uploadat September 8, 2008 with 3 comments
-
Basic JS Function to Show/Hide (Toggle) an Elementat November 12, 2008 with 1 comment
-
Creating the array_isearch() Functionat November 8, 2008

4 Replies to "Equivalent of PHP’s in_array() function"
September 13, 2008 at 5:44 AM
More concise:
function in_array(string, array) {
for(var i=0; i<array.length; i++) {
if (array[i] == string) return true;
}
return false;
}
September 25, 2008 at 4:13 AM
Even better:
Array.prototype.in_array = function(str){
for(var i=0; i<this.length; i++)
if (this[i] == str)
return true;
return false
}
August 31, 2009 at 2:07 PM
Hey quick question. How the heck do you get javascript to work when there is a field name like: name=”state[]” due to php requirement for the check boxes??
January 18, 2010 at 7:59 PM
Even more concise (Array.prototype.in_array adds the fonction string in the array !) :
function in_array (string, array) {
for (i in array) if(array[i] == string) return true;
return false;
};