I want to compare two arrays in PHP

前端 未结 6 1746
萌比男神i
萌比男神i 2021-01-20 23:45

Assume that I have two arrays as follow:

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

How to check that

相关标签:
6条回答
  • 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 讨论(0)
  • 2021-01-21 00:07

    Create a class containing an array and make that class implement the Comparable interface, for example http://php.net/manual/language.oop5.interfaces.php#69467

    0 讨论(0)
  • 2021-01-21 00:08

    In the simplest case you can just use array_diff. It ignores the keys in your second array, but also the order of the values. It would return an empty set if the arrays are equal:

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

    You could also compare the arrays directly, after stripping keys from the second:

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

    That would additionally compare the order of contained values.

    0 讨论(0)
  • 2021-01-21 00:08

    Try this

    $array1 = array(1, 3, 5);
    $array2 = array('x'=> 1, 'y'=> 2, 'z'=> 5);
    $array2 = array_values($array2);
    echo $array1 == $array2 ? 'true' : 'false';
    
    0 讨论(0)
  • 2021-01-21 00:14
     array_values($array1) === array_values($array2)
    

    Assuming that arrays have same order.

    0 讨论(0)
  • 2021-01-21 00:17

    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 讨论(0)
提交回复
热议问题