Use PHP functions in JavaScript

JavaScript array_reverse

Return input as a new array with the order of the entries reversed

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
38
39
4041
42
43
function array_reverse (array, preserve_keys) {
    // Return input as a new array with the order of the entries reversed  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/array_reverse    // +   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;
}
external links: original PHP docs | raw js source

Examples

Running

1
array_reverse( [ 'php', '4.0', ['green', 'red'] ], true);

Should return

1
{ 2: ['green', 'red'], 1: 4, 0: 'php'}

Dependencies

No dependencies, you can use this function standalone.

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have array_reverse goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Rafał
20 Sep '11 Permalink

q  @Paul: I changed the function, so it returns Array when preserve_keys is falsy.
https://github.com/kvz/phpjs/blob/master/functions/array/array_reverse.js
I think it was the first and last time I've touched array functions.

Gravatar
Paul
20 Sep '11 Permalink

q  When you pass a flat array (no direct keys) of just strings, and even set

 preserve_keys 

to false, you of course keep getting an object returned, and not an array as

  tmp_arr = {} 

and not

 tmp_arr = [] 



So in the case of there being no supplied keys in the array this does not seem to work.


  a = ["a", "b", "c"];
 
  b = PhpJs.array_reverse(a);



display b and you get [object Object] under QtScript at least.

Change to

 tmp_arr = [] 



... and you get the expected c, b, a

Does the function need to test on preserve_keys first as to what

 temp_arr 

is created as?

Gravatar
makanaki
9 Feb '11 Permalink

q  At least when there's no flag " preserve_keys" this function should return array, not object.

Gravatar
Kevin van Zonneveld
18 Nov '08 Permalink

q  @ frame: Yeah php.js is by no means ready. New functions are written and bugs are being fixed. It's a good idea to update your version every once in a while.

Gravatar
frame
18 Nov '08 Permalink

q  hmm .. i have downloaded the lib again and now there are the missing functions included.. please ignore..

Gravatar
frame
18 Nov '08 Permalink

q  Some functions are not included in php.js or php.min.js.. why?

do you forget to?

ex: file_exists, array_reserve

Gravatar
Also...
21 Mar '08 Permalink

q  Also from the site I just mentioned, here's a function which returns a genuine array (this could probably be combined with your function to test for preserve_keys and if not present, return a genuine array?):
[CODE="Javascript"]function array_reverse(arr) {
/* Simulate copy by value */
var arr_rev = [];
for (var i = 0; i < arr.length; i++) {
arr_rev[i] = arr[i];
}
arr_rev.reverse();
return arr_rev;
}[/CODE]

Gravatar
Brett Zamir
21 Mar '08 Permalink

q  Seems you've already done a whole lot of work, but not knowing about your site, I had started a wiki to keep this kind of information: http://javascript.wikia.com/wiki/PHP-Javascript . There are a few functions there presently, but please feel free to consider hosting this at such a wiki so it can be easily maintained by the whole community! Thanks! Email me at brettz9 & yahoo if you like.

Gravatar
Kevin van Zonneveld
16 Feb '08 Permalink

q  @ Karol Kowalski: That's solid work you can take pride in Karol, thank you!

Gravatar
Karol Kowalski
12 Feb '08 Permalink

q  Hello,
I've done some code refactoring, making the code do what it really needs to do (there's no need for the 2nd loop, it there?). I've run a test and it seems to be 38% faster. Here's the code
[CODE="Javascript"]
function array_reverse( array, preserve_keys ) {
// http://kevin.vanzonneveld.net
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: array_reverse( [ 'php', '4.0', ['green', 'red'] ], true );
// * returns 1: { 2: ['green', 'red'], 1: 4, 0: 'php'}

var i=0, f, key, keys = [], key_cnt=0, tmp_ar = {};

for(key in array){
keys[i++] = key;
}
keys = keys.reverse();
key_cnt = keys.length;
for( i=0; i < key_cnt; i++ ){
tmp_ar[(preserve_keys ? keys[i] : i)] = array[keys[i]];
}

return tmp_ar;
}

function array_reverse2( array, preserve_keys ) {
// http://kevin.vanzonneveld.net
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: array_reverse( [ 'php', '4.0', ['green', 'red'] ], true );
// * returns 1: { 2: ['green', 'red'], 1: 4, 0: 'php'}

var arr_len=array.length, newkey=0, tmp_ar = {}

for(var key in array){
newkey=arr_len-key-1;
tmp_ar[(!!preserve_keys)?newkey:key]=array[newkey]
}


return tmp_ar;
}

// wrapped in windows onload cause
// Firebug 1.1 throws an error otherwise

window.onload=function () {

console.time('array_reverse')

for (var i=10000;i;i--) {

array_reverse( [ 'php', '4.0', ['green', 'red'] ], true );

}

console.timeEnd('array_reverse')


console.time('array_reverse2')

for (var i=10000;i;i--) {

array_reverse2( [ 'php', '4.0', ['green', 'red'] ], true );

}

console.timeEnd('array_reverse2')

}
[/CODE]


Contribute a New function