Page 1 of 1

in_array( ) PHP Equivalent function in Javascript

PostPosted: August 18th, 2008, 10:33 am
by Shahzad Butt
If you are a PHP Developer, you certainly will be enjoying the PHP Array builtin functions which are very useful in performing common tasks related to Arrays.

One of the Array function is in_array() used to check the existance of an element in an array. It returns true if the element exists in the array and return false otherwise.

I just have developed its equivalent function in javascript and am sharing with you guys.

Code: Select all
   function in_array(sElement, sArray)
   {
      var bFlag = false;

      for(var i = 0; i < sArray.length; i ++)
      {
         if(sElement == sArray[i])
         {
            bFlag = true;

            break;
         }
      }

      return bFlag;
   }


Usage:
Its usage is just like the php function. Pass the element and the array name to it, and it will return you the result.
Code: Select all
var sCode = 123;
var sList = new Array(1234, 234, 5678, 123, 456);

if (in_array(sCode, sList) == true)
     alert("Element Found!");

else
     alert("Element not found!");

Re: in_array( ) PHP Equivalent function in Javascript

PostPosted: August 18th, 2008, 10:38 am
by Web Guru
The above function is really very useful in performing common tasks related to arrays but you can make it a part of Array functions in you application in the following manner.

Code: Select all
   Array.prototype.in_array = function(sElement)
   {
      var bFlag = false;

      for(var i = 0; i < this.length; i ++)
      {
         if(sElement == this[i])
         {
            bFlag = true;

            break;
         }
      }

      return bFlag;
   }


After declaring this function as a part of function available with arrays, your function call will be as follows:

Code: Select all
var sCode = 123;
var sList = new Array(1234, 234, 5678, 123, 456);

if (sList.in_array(sCode) == true)
     alert("Element Found!");

else
     alert("Element not found!");


I hope this will make things simple :)