簡體   English   中英

PHP如何檢查兩個數組的相等性

[英]PHP how to check for equality of two arrays

好吧,我不知道為什么我無法在下面的代碼上工作:

    $test1 = array(6500,6537,3013);
    $test2 = array(223,6500);
    if ( in_array( $test1, $test2) ) {
        echo "something is there";
    }

當數組test2存在來自test1至少一個值時,我正在嘗試獲取true

根據此處的示例3,它應該可以正常工作。

您需要使用array_intersect() in_array 考慮在“針”作為不同的個體值陣列測試。 它對整個陣列進行整體測試。

例如

php > $arr = array(1,2,3,array(4,5));
php > $test1 = array(1,3);
php > $test2 = array(4,5);

php > var_dump(in_array($test1, $arr));
bool(false)
php > var_dump(in_array($test2, $arr));
bool(true)

php > var_dump(array_intersect($test1, $arr));
PHP Notice:  Array to string conversion in php shell code on line 1
PHP Notice:  Array to string conversion in php shell code on line 1
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(3)
}

in_array —檢查數組中是否存在值,值得知道in_array將檢查精確值(關於其數據類型)。

在您的示例中,您的條件永遠不會返回true。

考慮以下示例:

php > $t1 = array(6500, 6537, 3013);
php > $t2 = array(223, 6500);

[223,6500]包括[6500,6537,3013]? 當然不。

php > echo in_array($t1, $t2) ? "something is here" : "nihil";
nihil
php > $x = 223;

[223,6500]包括223嗎? 是。 因此,它將打印“這里有東西”。

php > echo in_array($x, $t2) ? "something is here" : "nihil";
something is here

php > $t1 = array(6500, 6537, 3013, 223);

數組[6500,6537,3013,223]是否包含數組[223,6500] 再次沒有。

php > echo in_array($t2, $t1) ? "something is here" : "nihil";
nihil
php > $t1 = array(223, 6500, 6537, 3013);

如果我們將223作為第一個(第零個)元素插入,則不會有任何變化。 [223,6500,6537,3013]數組內部沒有[223,6500]數組。

php > echo in_array($t2, $t1) ? "something is here" : "nihil";
nihil

[[223,6500],6537,3013]包括[223,6500]。

php > $t1 = array(array(223, 6500), 6537, 3013);
php > echo in_array($t2, $t1) ? "something is here" : "nihil";
something is here

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM