Fork me on GitHub

Learn how to do it in JavaScript. Explore boundaries porting languages. Enjoy functions that turn out to be useful.

Here’s what a JavaScript equivalent for PHP’s array_intersect looks like.

function array_intersect (arr1) {
  //  discuss at: http://phpjs.org/functions/array_intersect/
  // original by: Brett Zamir (http://brett-zamir.me)
  //        note: These only output associative arrays (would need to be
  //        note: all numeric and counting from zero to be numeric)
  //   example 1: $array1 = {'a' : 'green', 0:'red', 1: 'blue'};
  //   example 1: $array2 = {'b' : 'green', 0:'yellow', 1:'red'};
  //   example 1: $array3 = ['green', 'red'];
  //   example 1: $result = array_intersect($array1, $array2, $array3);
  //   returns 1: {0: 'red', a: 'green'}

  var retArr = {},
    argl = arguments.length,
    arglm1 = argl - 1,
    k1 = '',
    arr = {},
    i = 0,
    k = ''

  arr1keys: for (k1 in arr1) {
    arrs: for (i = 1; i < argl; i++) {
      arr = arguments[i]
      for (k in arr) {
        if (arr[k] === arr1[k1]) {
          if (i === arglm1) {
            retArr[k1] = arr1[k1]
          }
          // If the innermost loop always leads at least once to an equal value, continue the loop until done
          continue arrs
        }
      }
      // If it reaches here, it wasn't found in at least one array, so try next value
      continue arr1keys
    }
  }

  return retArr
}
View on GitHub Edit on GitHub Source on GitHub

PHP arrays and JavaScript

Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are the closest we can get to this hashtable-like data structure without rolling our own. While many JavaScript implementations preserve the order of object properties, the ECMAScript Language Specification explicitly states that:

The mechanics and order of enumerating the properties is not specified.

So don't use this for anything serious if you rely on the order to be consistent accross platforms.

A community initiative

php.js offers community built functions and goes by the McDonald’s Theory. We’ll put online functions that aren't perfect, in the hopes to spark better contributions. Do you have one? You can directly edit this file on GitHub, this will create a Pull Request that the core team can review, and merge into our codebase.

This way of working also means that we don't offer any production guarantees, and recommend to use php.js inspiration and learning purposes only.

Notes

These only output associative arrays (would need to be all numeric and counting from zero to be numeric)

Example 1

$array1 = {'a' : 'green', 0:'red', 1: 'blue'};
$array2 = {'b' : 'green', 0:'yellow', 1:'red'};
$array3 = ['green', 'red'];
$result = array_intersect($array1, $array2, $array3);
Should return:
{0: 'red', a: 'green'}

« More array functions