php中判斷數組相等的方法以及數組運算子介紹_php技巧

來源:互聯網
上載者:User

如何判斷兩個數組相等呢?其實很簡單,用 == 或者 === 就可以了
php手冊裡說明如下:

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

複製代碼 代碼如下:

<?php
$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

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

複製代碼 代碼如下:

<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");

$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);

$c = array_merge($a, $b); // Union of $b and $a
echo "array_merge of \$b and \$a: \n";
var_dump($c);
?>

執行後輸出:

複製代碼 代碼如下:

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"
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.