in_array( ) PHP Equivalent function in Javascript

This section contains a lot of Scripting material for your website.

in_array( ) PHP Equivalent function in Javascript

Postby Shahzad Butt on August 18th, 2008, 10:33 am

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!");
Regards
Shahzad Butt
http://www.GeoSourceCode.com
Shahzad Butt
 
Posts: 24
Joined: July 9th, 2008, 11:16 am
Location: Pakistan

Re: in_array( ) PHP Equivalent function in Javascript

Postby Web Guru on August 18th, 2008, 10:38 am

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 :)
User avatar
Web Guru
 
Posts: 75
Joined: March 24th, 2008, 7:59 am
Location: Lahore, Pakistan


Return to Java Script / VB Script

Who is online

Users browsing this forum: No registered users and 0 guests