Equivalent of PHP’s in_array() function

Posted on September 13, 2008, under JavaScript,  Bookmark it

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!

Get our RSS Feed!

Related Posts

6 Replies to "Equivalent of PHP’s in_array() function"

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

  2. Even better:

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

  3. 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. 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;
    };

  5. 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.

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;)