Jump to content

In_array function


makeshift_theory

Recommended Posts

Well I pondered this for a while and came up with a way to detect if a object is in a array.  I would like to see if this code can be optmized due to the fact I haven't gotten that far in my JS studies yet  ;D.  These functions will allows for you to search for a array needle and array haystack and a string needle and array haystack.

[code]function isArray() {
if (typeof arguments[0] == 'object') { 
var criterion = arguments[0].constructor.toString().match(/array/i);
return (criterion != null); 
}
return false;
}

function in_array(needle, haystack)
{ // This will loop through a haystack to find a needle which is an array
var hlen = haystack.length; // length of haystack
var nlen = needle.length; // length of needle
if(isArray(needle))
{
for(var i=0;i <= hlen;i++)
{ // loop through all element in array
for(var z=0;z < nlen;z++)
{
if(needle[z] == haystack[i])
return true;
else
return false;
}
}
}
else
{ // Not an array
for(var i=0;i <= hlen;i++)
{
if(needle == haystack[i])
return true;
else
return false;
}
}
}[/code]
Link to comment
https://forums.phpfreaks.com/topic/35808-in_array-function/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.