---
layout: page
title: "JavaScript array_reverse function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/array_reverse:334
- /functions/view/array_reverse
- /functions/view/334
- /functions/array_reverse:334
- /functions/334
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's array_reverse

{% codeblock array/array_reverse.js lang:js https://raw.github.com/kvz/phpjs/master/functions/array/array_reverse.js raw on github %}
function array_reverse (array, preserve_keys) {
  // From: http://phpjs.org/functions
  // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: Karol Kowalski
  // *     example 1: array_reverse( [ 'php', '4.0', ['green', 'red'] ], true);
  // *     returns 1: { 2: ['green', 'red'], 1: 4, 0: 'php'}
  var isArray = Object.prototype.toString.call(array) === "[object Array]",
    tmp_arr = preserve_keys ? {} : [],
    key;

  if (isArray && !preserve_keys) {
    return array.slice(0).reverse();
  }

  if (preserve_keys) {
    var keys = [];
    for (key in array) {
      // if (array.hasOwnProperty(key)) {
      keys.push(key);
      // }
    }

    var i = keys.length;
    while (i--) {
      key = keys[i];
      // FIXME: don't rely on browsers keeping keys in insertion order
      // it's implementation specific
      // eg. the result will differ from expected in Google Chrome
      tmp_arr[key] = array[key];
    }
  } else {
    for (key in array) {
      // if (array.hasOwnProperty(key)) {
      tmp_arr.unshift(array[key]);
      // }
    }
  }

  return tmp_arr;
}
{% endcodeblock %}

 - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/array/array_reverse.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_reverse.js)

### Example 1
This code
{% codeblock lang:js example %}
array_reverse( [ 'php', '4.0', ['green', 'red'] ], true);
{% endcodeblock %}

Should return
{% codeblock lang:js returns %}
{ 2: ['green', 'red'], 1: 4, 0: 'php'}
{% endcodeblock %}


### Other PHP functions in the array extension
{% render_partial _includes/custom/array.html %}
