php 判斷兩個數組是否相等

來源:互聯網
上載者:User

標籤:dump   col   執行   判斷   class   比較   pre   ber   如何   

如何判斷兩個數組相等呢?其實很簡單,用 == 或者 === 就可以了

那像 array(‘k‘=>array())這樣的多維陣列能用如上方法判斷相等嗎?當然也可以。
若數組是數字索引的,就要注意一下了,見代碼:

1 <?php2     $a = array("apple", "banana");3     $b = array(1 => "banana", "0" => "apple");4 5     var_dump($a == $b); // bool(true)6     var_dump($a === $b); // bool(false)7 ?>

除了==這種數組操作符之外,還有其他比較繞的方法來判斷。比如說,利用array_diff($a, $b)來比較兩個數組的差集,如果差集是空數組的話就相等了。
然後再說一下 數組的 + 加號運算子。+ 和 array_merge的區別在遇到相等key時,用+時,左邊數組會覆蓋掉右邊數組的值,array_merge相反,後面的數組覆蓋掉前面的。

 1 <?php 2     $a = array("a" => "apple", "b" => "banana"); 3     $b = array("a" => "pear", "b" => "strawberry", "c" => "cherry"); 4  5     $c = $a + $b; // Union of $a and $b 6     echo "Union of \$a and \$b: \n"; 7     var_dump($c); 8  9     $c = array_merge($a, $b); // Union of $b and $a10     echo "array_merge of \$b and \$a: \n";11     var_dump($c);12 ?>

執行後輸出:

Union of $a and $b:array(3) {  ["a"]=>  string(5) "apple"  ["b"]=>  string(6) "banana"  ["c"]=>  string(6) "cherry"}array_merge of $b and $a:array(3) {  ["a"]=>  string(4) "pear"  ["b"]=>  string(10) "strawberry"  ["c"]=>  string(6) "cherry"}

 

php 判斷兩個數組是否相等

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.