Equivalent of PHP’s in_array() function

Posted on September 13, 2008, under JavaScript 

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">
  <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">


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.");
  alert(str_to_check +" is not in our array.");



If you have any comments or suggestions regarding this script please post them.

Comment via Facebook


Leave a Reply

* = required fields

  (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)


  • The comment must be relevant with the topic of the post.
  • Only comments with real email addresses will get approved. So, emails like 'abc@domain.com' will not be accepted.
  • Do not post the same message in multiple articles through the site.
  • Do not post advertisements, junk mail or pyramid schemes.
  • In case you post a link to another site, please explain briefly where the link goes as a courtesy to other users.
  • Do not post comments such as: "Thank you", "Awesome", "Nice tutorial", "Merci", etc.