UNPKG

phpjs

Version:

php.js offers community built php functions in javascript

87 lines (71 loc) 2.53 kB
--- layout: page title: "JavaScript array_flip function" comments: true sharing: true footer: true alias: - /functions/view/array_flip:317 - /functions/view/array_flip - /functions/view/317 - /functions/array_flip:317 - /functions/317 --- <!-- Generated by Rakefile:build --> A JavaScript equivalent of PHP's array_flip {% codeblock array/array_flip.js lang:js https://raw.github.com/kvz/phpjs/master/functions/array/array_flip.js raw on github %} function array_flip (trans) { // From: http://phpjs.org/functions // + 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; } {% endcodeblock %} - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/array/array_flip.js) 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](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online functions that are far from perfect, in the hopes to spark better contributions. Do you have one? Then please just: - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/array/array_flip.js) ### Example 1 This code {% codeblock lang:js example %} array_flip( {a: 1, b: 1, c: 2} ); {% endcodeblock %} Should return {% codeblock lang:js returns %} {1: 'b', 2: 'c'} {% endcodeblock %} ### Example 2 This code {% codeblock lang:js example %} ini_set('phpjs.return_phpjs_arrays', 'on'); array_flip(array({a: 0}, {b: 1}, {c: 2}))[1]; {% endcodeblock %} Should return {% codeblock lang:js returns %} 'b' {% endcodeblock %} ### Other PHP functions in the array extension {% render_partial _includes/custom/array.html %}