Compare 2 arrays ???

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Sacapuss
Forum Commoner
Posts: 40
Joined: Mon May 16, 2005 9:46 pm
Location: Earth...

Compare 2 arrays ???

Post by Sacapuss »

Hi !

Could you let me know how i could, with javascript, detect that 2
arrays contain the same elements, please ?

Thanx for your help !
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Code: Select all

var array1 = new Array(
    'one',
    'two',
    'three'
);

var array2 = new Array(
    'one',
    'two',
    'three'
);

var array3 = new Array(
    'not one',
    'two',
    'not four'
);

function arrayDiffer(arr1, arr2) {
    //Get length of array (and check for equal length)
    l1 = arr1.length;
    l2 = arr2.length;
    if (l1 != l2) {
        return false;
    }
    for (theKey in arr1) { //Check each element in array1 is same as respective element is array2
        if (arr1їtheKey] != arr2їtheKey]) {
            return false;
        }
    }
    return true;
}
User avatar
Sacapuss
Forum Commoner
Posts: 40
Joined: Mon May 16, 2005 9:46 pm
Location: Earth...

Thanx for your answer, d11wtq !

Post by Sacapuss »

Thanx for your answer, d11wtq !
thedamo
Forum Newbie
Posts: 9
Joined: Fri Jul 15, 2005 7:23 am
Location: Sydney Australia

Post by thedamo »

maybe I have not understood the question, but could you just use the array_diff() function to if it returns a 0 length array, you then know that they are the same.

e.g.

Code: Select all

$myArray = array_diff($array1, $array2);
if(count($myArray) < 1)
print(&quote;arrays are the same&quote;);
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

this was for JS, not php...
Post Reply