in_array( ) PHP Equivalent function in Javascript
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.
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.
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!");