Fork me on GitHub

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

JavaScript array_flip function

A JavaScript equivalent of PHP’s array_flip

array/array_flip.js raw on github
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function array_flip(trans) {
  //  discuss at: http://phpjs.org/functions/array_flip/
  // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: Pier Paolo Ramon (http://www.mastersoup.com/)
  // improved by: Brett Zamir (http://brett-zamir.me)
  //  depends on: array
  //        test: skip
  //   example 1: array_flip( {a: 1, b: 1, c: 2} );
  //   returns 1: {1: 'b', 2: 'c'}
  //   example 2: ini_set('phpjs.return_phpjs_arrays', 'on');
  //   example 2: array_flip(array({a: 0}, {b: 1}, {c: 2}))[1];
  //   returns 2: 'b'

  var key, tmp_ar = {};

  // Duck-type check for our own array()-created PHPJS_Array
  if (trans && typeof trans === 'object' && trans.change_key_case) {
    return trans.flip();
  }

  for (key in trans) {
    if (!trans.hasOwnProperty(key)) {
      continue;
    }
    tmp_ar[trans[key]] = key;
  }

  return tmp_ar;
}

Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are the closest match to this hashtable-like data structure.

Please also note that php.js offers community built functions and goes by the McDonald’s Theory. We’ll put online functions that are far from perfect, in the hopes to spark better contributions. Do you have one? Then please just:

Other PHP functions in the array extension

Comments