Equivalent of PHP’s in_array() function

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



  1. Darren says

    Thank you for this code it helped out a lot.

    In regards to John the POST variable automatically converts to a PHP array so that is how you do it. You loop through the PHP array equivalent.

  2. says

    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;

  3. says

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

  4. Tim says

    Even better:

    Array.prototype.in_array = function(str){
    for(var i=0; i<this.length; i++)
    if (this[i] == str)
    return true;
    return false

  5. z says

    More concise:
    function in_array(string, array) {
    for(var i=0; i<array.length; i++) {
    if (array[i] == string) return true;
    return false;

Leave a Reply

Your email address will not be published. Required fields are marked *