30
Jan
var test_array = new Array(’jack’, ’joey’, ’phillip’, ’peter’, ’jane’); var assoc_array = new Array(); assoc_array[’sarah’] = 25; assoc_array[’samantha’] = 22; assoc_array[’joseph’] = 26; assoc_array[’jack’] = 28; assoc_array[’joey’] = 27; assoc_array[’peter’] = 25; // Example 1: value found if( in_array(’jack’, test_array) ) { alert(’Aha…found you jack!’); } // Example 2: value not found if( !in_array(’jasmine’, test_array) ) { alert(’Where are you dear jasmine?’); } // Example 3: search by array key if( in_array(’sarah’, assoc_array, ’key’) ) { alert(assoc_array[’sarah’]); } Code: /** * Simulate PHP in_array() function. * This will NOT recursively search the array depth. * * @param needle what to search for * @param haystack the array in which to search for a value matching needle. * This is assumed to be non-associative * @param assoc options: key/value. * key = search for needle in the keys of the associative array. * value = search for the needle in the values * If any other string is passed it will default to value. * @return bool */ function in_array(needle, haystack, assoc) { if( !assoc || assoc == ’’ ) { for( var i=0; i<haystack.length; i++ ) { if( haystack[i] == needle ) { return true; } } } else { if( assoc == ’key’ ) { for( var key in haystack) { if( key == needle ) { return true; } } } else { for( var key in haystack ) { if( haystack[key] == needle ) { return true; } } } } return false; }




