I want to compare two arrays in PHP

Suppose I have two arrays:

$array1 = array(1, 3, 5);
$array2 = array('x'=> 1, 'y'=> 2, 'z'=> 5);

      

How to check that two arrays are equally the most efficient and correct and it doesn't need the * $ array2 keywords .

I want to create a function that should return true if the values ​​are exactly the same, and false if any of them differ in both value (values) and number of elements.

Thanks for your time and reading.

+3


source to share


6 answers


 array_values($array1) === array_values($array2)

      



Assuming the arrays are the same order.

+3


source


In the simplest case, you can just use array_diff

. It ignores the keys in the second array as well as the order of the values. It will return an empty set if the arrays are equal:

 if (count(array_diff($array1, $array2)) == 0) {
    // equal

      

You can also compare arrays directly, after removing the keys from the second:



 if ($array1 == array_values($array2)) {

      

This will additionally compare the order of the contained values.

+4


source


try it

$array1 = array(1, 3, 5);
$array2 = array('x'=> 1, 'y'=> 2, 'z'=> 5);
$array2 = array_values($array2);
echo $array1 == $array2 ? 'true' : 'false';

      

+1


source


like this:

<?php    
$array1 = array ("a" => "green", "b" => "brown", "c" => "blue", "red");    
$array2 = array ("a" => "green", "yellow", "red");    
$result = array_diff($array1, $array2);    
if(count($result) == 0)
{
  .......  
}    
?>

      

0


source


array_diff will do the job for you:

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
if(empty($result)){
    // arrays contain the same values!
}

?>

      

0


source


Create a class containing an array and create this class for the Comparable interface like http://php.net/manual/language.oop5.interfaces.php#69467

0


source







All Articles