JavaScript equivalent of PHP's in_array()
No, it doesn't have one. For this reason most popular libraries come with one in their utility packages. Check out jQuery's inArray and Prototype's Array.indexOf for examples.
jQuery's implementation of it is as simple as you might expect:
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
If you are dealing with a sane amount of array elements the above will do the trick nicely.
EDIT: Whoops. I didn't even notice you wanted to see if an array was inside another. According to the PHP documentation this is the expected behavior of PHP's in_array
:
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found\n";
}
if (in_array(array('f', 'i'), $a)) {
echo "'fi' was found\n";
}
if (in_array('o', $a)) {
echo "'o' was found\n";
}
// Output:
// 'ph' was found
// 'o' was found
The code posted by Chris and Alex does not follow this behavior. Alex's is the official version of Prototype's indexOf, and Chris's is more like PHP's array_intersect
. This does what you want:
function arrayCompare(a1, a2) {
if (a1.length != a2.length) return false;
var length = a2.length;
for (var i = 0; i < length; i++) {
if (a1[i] !== a2[i]) return false;
}
return true;
}
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(typeof haystack[i] == 'object') {
if(arrayCompare(haystack[i], needle)) return true;
} else {
if(haystack[i] == needle) return true;
}
}
return false;
}
And this my test of the above on it:
var a = [['p','h'],['p','r'],'o'];
if(inArray(['p','h'], a)) {
alert('ph was found');
}
if(inArray(['f','i'], a)) {
alert('fi was found');
}
if(inArray('o', a)) {
alert('o was found');
}
// Results:
// alerts 'ph' was found
// alerts 'o' was found
Note that I intentionally did not extend the Array prototype as it is generally a bad idea to do so.
Javascript in_array
You can use Array.prototype.find()
:
var data = ['Lorem', 'Ipsum', 'Sit']
var foundSit = data.find(function(item){
return item == 'Sit';
});
Does PHP's ArrayObject have an in_array equivalent?
No. Even ignoring the documentation, you can see it for yourself
echo '<pre>';
print_r( get_class_methods( new ArrayObject() ) );
echo '</pre>';
So you are left with few choices. One option, as you say, is to cast it
$a = new ArrayObject( array( 1, 2, 3 ) );
if ( in_array( 1, (array)$a ) )
{
// stuff
}
Which is, IMO, the best option. You could use the getArrayCopy() method but that's probably more expensive than the casting operation, not to mention that choice would have questionable semantics.
If encapsulation is your goal, you can make your own subclass of ArrayObject
class Whatever extends ArrayObject
{
public function has( $value )
{
return in_array( $value, (array)$this );
}
}
$a = new Whatever( array( 1, 2, 3 ) );
if ( $a->has( 1 ) )
{
// stuff
}
I don't recommend iteration at all, that's O(n) and just not worth it given the alternatives.
What is PHP's equivalent of JavaScript's array.every() ?
Use a for loop with an early return.
PHP does not have a native function that performs the same function as Javascript's array#every.
PHP's in_array bevahior surprises me
You need to use the "strict" setting, to force the function to check the types of the elements as well:
var_dump(in_array('aaa', [0, 1], true));
http://php.net/manual/en/function.in-array.php states
If the third parameter strict is set to TRUE then the in_array()
function will also check the types of the needle in the haystack.
The reason it returns true is because a string is truthy, and so is 1
.
if( "aaa" ){ echo "you will see me"; }
Javascript push_array and in_array
You're looking for the push
method and the indexOf
method.
Note that indexOf
is not supported by IE, so you'll need to implement it yourself, like this:
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(searchElement /*, fromIndex */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (len === 0)
return -1;
var n = 0;
if (arguments.length > 0)
{
n = Number(arguments[1]);
if (n !== n) // shortcut for verifying if it's NaN
n = 0;
else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
if (n >= len)
return -1;
var k = n >= 0
? n
: Math.max(len - Math.abs(n), 0);
for (; k < len; k++)
{
if (k in t && t[k] === searchElement)
return k;
}
return -1;
};
}
(copied from MDC)
Why does php's in_array return true if passed a 0?
It's because by default in_array
uses loose comparisons, so when you pass 0
as an input it attempts to convert the string values in the array to an integer, and they all come out as 0 (because none of them start with a digit; see the manual), causing in_array
to return true
. It returns false for an input of 1
because all the comparison values are 0.
You will see similar behaviour with array_keys
:
print_r(array_keys($array, 0));
Output:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
indicating that array_keys
thinks every value in the array is 0.
If you use the strict
parameter to in_array
or array_keys
you will avoid this issue i.e.
echo in_array(0, $array, true) ? '0 is also in the array!' : '0 is NOT in the array!';
print_r(array_keys($array, 0, true));
Output:
0 is NOT in the array!
Array
(
)
Demo on 3v4l.org
Check if Variable in array javascript
There's no native "in_array"-function in JavaScript (as in PHP), check out this solution:
http://phpjs.org/functions/in_array:432
Also a search would have lead you here:
JavaScript equivalent of PHP's in_array()
Strange usage of in_array
The double question mark IS in fact the null coalesce operator, new in PHP 7:
http://php.net/manual/de/migration70.new-features.php
in_array() will return false if haystack is an empty array, in fact it will only return TRUE if the needle is found in haystack. Read the documentation here:
http://php.net/manual/de/function.in-array.php
Related Topics
Include PHP Inside JavaScript (.Js) Files
Manipulate a String That Is 30 Million Characters Long
PHP Output Showing Little Black Diamonds With a Question Mark
Get Everything Between ≪Tag≫ and ≪/Tag≫ With PHP
: Operator (The 'Elvis Operator') in PHP
Who Should Handle the Conditions in Complex Queries, the Data Mapper or the Service Layer
PHP: Warning: Sort() Expects Parameter 1 to Be Array, Resource Given
Date Difference in PHP on Days
Difference Between "Not Equal" Operators ≪≫ and != in PHP
How to List All Months Between Two Dates
Disable Warnings When Loading Non-well-formed HTML by Domdocument (PHP)
PHP Json_Encode Class Private Members
Listing All the Folders Subfolders and Files in a Directory Using PHP
Is There a PHP Equivalent of Perl'S Www::Mechanize
Which $_Server Variables Are Safe
In PHP (≫= 5.0), Is Passing by Reference Faster