Please login or register. Welcome to the Studio, guest!


Quick Links:


newBookmarkLockedFalling

Zero Tolerance

Zero Tolerance Avatar

*
New Member

21


October 2005
The following javscript function emulates phps 'in_array', this nifty function searches through an array to check if a value is within the array, it will also support any level of a multi dimensional array (arrays within arrays). However with that said, I don't suggest using this on a massive multi dimensional array, not sure how quickly it'd execute, but feel free to crash test it =P

in_array = function(_needle, _haystack)
{
       if (typeof _haystack == 'object')
       {
               for (n = 0; n < _haystack.length; n++)
               {
                       if (_needle == _haystack[n])
                       {
                               return true
                       }

                       if (typeof _haystack[n] == 'object')
                       {
                               return in_array(_needle, _haystack[n])
                       }
               }
       }

       return false
}


Usage:
if (in_array('find me', searchArray))
{
alert('found')
}
else
{
alert('not found')
}


As you've guessed, the function returns true on success, and false on failure.

Hope this is of some use :)

- Zero Tolerance


Last Edit: Nov 4, 2005 17:33:58 GMT by Zero Tolerance

crazynarutard

crazynarutard Avatar

*****
Senior Studio Member

1,470


August 2005
That's not build into PHP? I thought it was :P

Chris

Chris Avatar

******
Head Coder

19,519


June 2005
This is for JavaScript he said. :P It clones the PHP function.

Good job ZT.

crazynarutard

crazynarutard Avatar

*****
Senior Studio Member

1,470


August 2005
cddude229 said:
This is for JavaScript he said. :P It clones the PHP function.

Good job ZT.

ooh...I knew that >_<

I was actually thinking about making one for JS, XD.
meh, I'm sleepy. leave me alone

Eric

Eric Avatar



1,442


November 2005
in_array = function(_needle, _haystack)
{
   if (typeof _haystack == 'object')
   {
      for (var n = 0; n < _haystack.length; n++)
      {
         if (_needle == _haystack[n])
            return true
            
         if (typeof _haystack[n] == 'object')
         {
            if(in_array(_needle, _haystack[n]))
               return true;

         }
      }
   }
   return false
}


There's my version of what you made.
What I changed:
  • In yours it would only check the first array if multidimensional, and if it didn't have it the function would return 0, ending the function and stopping future checking. I fixed that by using an if check to see if the value was true, and if so then return it.
  • A problem that I ran into is that n was a global variable, so I had to make it local, otherwise doing it my way it would continuously loop through the same things.


:P

newBookmarkLockedFalling