php中判斷數(shù)組相等的方法以及數(shù)組運算符介紹
如何判斷兩個數(shù)組相等呢?其實很簡單,用 == 或者 === 就可以了
php手冊里說明如下:
那像 array('k'=>array())這樣的多維數(shù)組能用如上方法判斷相等嗎?當(dāng)然也可以。
若數(shù)組是數(shù)字索引的,就要注意一下了,見代碼:
<?php
$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");
var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>
除了==這種數(shù)組操作符之外,還有其他比較繞的方法來判斷。比如說,利用array_diff($a, $b)來比較兩個數(shù)組的差集,如果差集是空數(shù)組的話就相等了。
然后再說一下 數(shù)組的 + 加號運算符。+ 和 array_merge的區(qū)別在遇到相等key時,用+時,左邊數(shù)組會覆蓋掉右邊數(shù)組的值,array_merge相反,后面的數(shù)組覆蓋掉前面的。
<?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);
?>
執(zhí)行后輸出:
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"
}
相關(guān)文章
php下foreach提示W(wǎng)arning:Invalid argument supplied for foreach()
這篇文章主要介紹了php下foreach提示W(wǎng)arning:Invalid argument supplied for foreach()的解決方法,是很多開發(fā)者在進(jìn)行PHP程序設(shè)計的過程中經(jīng)常會遇到的問題,需要的朋友可以參考下2014-11-11php實現(xiàn)連接access數(shù)據(jù)庫并轉(zhuǎn)txt寫入的方法
這篇文章主要介紹了php實現(xiàn)連接access數(shù)據(jù)庫并轉(zhuǎn)txt寫入的方法,涉及php連接、讀取access數(shù)據(jù)庫及寫入txt文件的相關(guān)操作技巧,需要的朋友可以參考下2017-02-02