-3
$array1 = array(1,1,1);  
$array2= array(1,5,9,2,2,1);

I need to compare $array2 with $array1 and if $array2 has the same identical values should return true, otherwise should be returning false. In this case it should return false

Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90
Rz --
  • 13
  • 3
  • http://stackoverflow.com/a/901831/1415724 (After Googling "compare arrays php") ;-) – Funk Forty Niner Sep 08 '13 at 17:06
  • So why don't you google on comparing arrays in php ... I bet 49Cents, you'll find your answer within 20 seconds... – djot Sep 08 '13 at 17:06
  • 1
    @djot Actually `About 1,040,000 results (0.22 seconds)` ;-) – Funk Forty Niner Sep 08 '13 at 17:08
  • @Fred -ii- But I unfortunately do not get 0.49Euro(!) for each ;) of them – djot Sep 08 '13 at 17:10
  • @djot LMAO! yeah and if I had a nickel for every time an OP doesn't bother Googling, I'd be a stockholder with Google ;-) – Funk Forty Niner Sep 08 '13 at 17:11
  • you are all so intelligent you find several results to compare arrays but not repeated array since if it finds a value, in_array turns true.. btw to use that method i need to use the same keys @Fred-ii- so clever – Rz -- Sep 08 '13 at 17:22
  • possible duplicate of [PHP compare array](http://stackoverflow.com/questions/901815/php-compare-array) – larrylampco Sep 11 '13 at 22:26
  • @larrylampco how about no, has nothing to do with it.. and i wrote the solution for this and post under there – Rz -- Sep 12 '13 at 00:41

3 Answers3

2

You can use the == and === operators.

$array1 == $array2 only checks if the two arrays contain the same key/value pairs and $array1 === $array2 also checks if they are in the same order and if they are of the same type.

See the PHP manual.

SharpKnight
  • 455
  • 2
  • 14
1
if ( $array1 == $array2 ) {
    return true;
}
else{
    return false;
}

Note: keys must be same too.


To check only values:

if(!array_diff($array1, $array2) && !array_diff($array2, $array1)) 
   return true;
Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90
1

Well thanks @Shadowfax for trying help but i made the solution, so i post here if anyone have the same problem..

function compareArrayValues($array1,$array2){
$result= array();
for ($a=0; $a< count($array1); $a++){
    $array2=array_values($array2);
    for ($b=0; $b < count($array2) ; $b++) { 
        if ($array1[$a] == $array2[$b]){
            array_push($result,$array1[$a]);
            unset($array2[$b]);
            break;
        }
    }

}
if ($result == $array1){
    return true;
}else{
    return false;
}
}
Rz --
  • 13
  • 3