Use PHP functions in JavaScript

JavaScript in_array

Checks if the given value exists in the array

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/in_array    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {                return true;
            }
        }
    }
     return false;
}
external links: original PHP docs | raw js source

Examples

» Example 1

Running

1
in_array('van', ['Kevin', 'van', 'Zonneveld']);

Should return

1
true

» Example 2

Running

1
in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});

Should return

1
false

Dependencies

No dependencies, you can use this function standalone.

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have in_array goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Brett Zamir
27 Nov '09 Permalink

q  @Jordi: Thanks for the submission. Kevin commented on this earlier that although he supports DRY (Don't Repeat Yourself), it is faster in this case to be longer, since with the way we have it now, there is only need to check the "strict" argument once. So, we will stick with the way it is.

Btw, if you are using your version, you should drop the first "if" since it prevents dealing with non-strict cases.

Thanks again!

Gravatar
Jordi
26 Nov '09 Permalink

q  Of course that had to be:

function in_array (needle, haystack, argStrict) 
{
    var key = '', strict = !!argStrict;

    if (strict)
        for (key in haystack)
            if ( (strict && haystack[key] === needle) || ( !strict && strict && haystack[key] == needle ) )
                return true;

    return false;
}


Gravatar
Jordi
26 Nov '09 Permalink

q  Shorter:

	function in_array (needle, haystack, argStrict) 
    {
		var key = '', strict = !!argStrict;

		if (strict)
			for (key in haystack)
				if ( (strict && haystack[key] === needle) ) || ( !strict && strict && haystack[key] == needle )
					return true;

		return false;
	}
    


Gravatar
Brett Zamir
18 Oct '09 Permalink

q  @billy: Thanks, fixed now in git: http://github.com/kvz/phpjs/commit/e37089b71ed1d32d1b4b4567c70a684c9d0e16f5

Sorry Drydenmaker and Kevin, it was a noble attempt, but search should be checked against -1, and even if that were corrected, there would still be problems as your version would make in_array('needle', ['needles']) return true.

Gravatar
Theriault
18 Oct '09 Permalink

q  I believe the solution to the bug Billy found is that the native JavaScript String.prototype.search returns -1 if the needle is not found, not false like in PHP, what this function expects.

Also, turning an array into a string and searching for the needle, while faster, will be incorrect in many situations, such as searching for 'he' against ['the'] will return true, even though 'he' is not in the array.

Gravatar
Billy
17 Oct '09 Permalink

q  Is it just me or does in_array("whatever", ["notit"]) return true...

This function is majorly broken. Strings arguments always return true, even if the array is empty!

Gravatar
Kevin van Zonneveld
8 Oct '09 Permalink

q  @ Drydenmaker: Good point. Didn't bench it but obviously an internal function would be faster than anything we can hack.

However your implementation relies on this.is_string which is not a php.js feature.
I replaced it with (typeof(needle)=='string') but it seems that also the second test case (where we don't want to find 'vlado') fails.
So it needs a little bit of work still.

Gravatar
Drydenmaker
22 Sep '09 Permalink

q  what if you flattened the non-strict side to a string and used a string search to avoid the loop. Something like:


in_array: function (needle, haystack, argStrict) {
            
            var key = '', strict = !!argStrict;
        
            if (strict) {
                for (key in haystack) {
                    if (haystack[key] === needle) {
                        return true;
                    }
                }
            } else {
				if (this.is_string(needle)) {
					str = haystack.toString();
					return (str.search(needle) !== false)
				}
				
                for (key in haystack) {
                    if (haystack[key] == needle) {
                        return true;
                    }
                }
            }
        
            return false;
        }

Gravatar
Kevin van Zonneveld
31 May '09 Permalink

q  @ vlado houba: Yes using hash tables is really fast. Obviously we don't control our user's data. But we can make an effort to make in_array as fast as reasonably possible, and I see your optimization is not to check for strict every iteration, but check for it once, and use duplicated loops to do further processing.

Though I'm a big fan of DRY, this really makes sense to me and justifies exception so I will implement your proposal. Thanks for sharing!

Gravatar
vlado houba
31 May '09 Permalink

q  sorry for posting that same content by mistake...

maybee it seems to be an unimporatnt change but i was working on a text analyzing script where things like this one matters a lot

for fast searching in small arrays i recommend using the value (string or number) as an index (for sure just for short values..), it much cuts the access times and can be used for advanced structures

function in_array(needle, haystack, argStrict)
{
	var found = new Boolean(false);
	var key;
	var strict = new Boolean(argStrict);
	if(strict)
	{
		for (key in haystack)
		{
			if (haystack[key] === needle)
			{
				found = true;
				break;
			}
		}
	}
	else
	{
		for (key in haystack)
		{
			if (haystack[key] == needle)
			{
				found = true;
				break;
			}
		}
	}
	return found;
}


Gravatar
Brett Zamir
5 Apr '09 Permalink

q  @Vladimir, it looks like you posted the same code as we currently have... One very small optimization I do see is "return true" and "return false" instead of found=true, etc. If your optimization was using indexOf, be aware that PHP.JS considers objects to be arrays, so we need to handle them as well...

Gravatar
Vladimir Houba
5 Apr '09 Permalink

q  function's preformance can be improoved by following

01.function in_array(needle, haystack, argStrict) {
02.    // Checks if the given value exists in the array 
03.    //
04.    // version: 903.1614
05.    // discuss at: http://phpjs.org/functions/in_array
06.    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
07.    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
08.    // *     returns 1: true
09.    var found = false, key, strict = !!argStrict;
10. 
11.    for (key in haystack) {
12.        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
13.            found = true;
14.            break;
15.        }
16.    }
 
    return found;
}

Gravatar
Kevin van Zonneveld
15 Feb '09 Permalink

q  @ Java Dude: No but it has been tested (successfully) in Rhino and I believe Google based their js engine on that.
Do you have more information (maybe a line number or something) for us to go on? Thanks in advance!

Gravatar
Java Dude
12 Feb '09 Permalink

q  Has this function been tested on Google Chrome?

I am receiving a: Uncaught TypError when using it but on in Google Chrome.

Gravatar
Kevin van Zonneveld
18 Jun '08 Permalink

q  @ peter: Thank you but according to the PHP manual in_array should return a boolean value. Also, your version doesn't support the optional strict argument, so in it's current form I'm not convinced I should replace our version with yours.

Gravatar
peter
17 Jun '08 Permalink

q  [CODE="Javascript"]
function in_array(value, arr)
{
var key;
for (key in arr)
{
if (arr[key] === value)
{return value; }
}
return null; //false
}
[/CODE]

Gravatar
Kevin van Zonneveld
12 May '08 Permalink

q  @ Adam: If I'm not mistaken this forces strict to be boolean. A single exclamation mark would indeed reverse it's meaning.

Gravatar
Adam
12 May '08 Permalink

q  [CODE="Javascript"]
var found = false, key, strict = !!strict;
[/CODE]

why are you defining strict to be NOT NOT strict ?


Contribute a New function