按鍵比較兩個PHP數組

[英]compare two PHP arrays by key


What's the fastest way to compare if the keys of two arrays are equal?

如果兩個數組的鍵相等,最快的比較方法是什么?

for eg.

array1:          array2:

'abc' => 46,     'abc' => 46,
'def' => 134,    'def' => 134,
'xyz' => 34,     'xyz' => 34, 

in this case result should be TRUE (same keys)

在這種情況下,結果應為TRUE(相同的鍵)

and:

array1:          array2:

'abc' => 46,     'abc' => 46,
'def' => 134,    'def' => 134,
'qwe' => 34,     'xyz' => 34, 
'xyz' => 34,    

result should be FALSE (some keys differ)

結果應為FALSE(某些鍵不同)

array_diff_key() returns a empty array...

array_diff_key()返回一個空數組......

3 个解决方案

#1


15  

Use array_diff_key, that is what it is for. As you said, it returns an empty array; that is what it is supposed to do.

使用array_diff_key,就是它的用途。如你所說,它返回一個空數組;這是應該做的。

Given array_diff_key($array1, $array2), it will return an empty array if all of array1's keys exist in array2. To make sure that the arrays are equal, you then need to make sure all of array2's keys exist in array1. If either call returns a non-empty array, you know your array keys aren't equal:

給定array_diff_key($ array1,$ array2),如果array2中存在所有array1的鍵,它將返回一個空數組。要確保數組相等,您需要確保array1中存在所有array2的鍵。如果任一調用返回非空數組,則表示您的數組鍵不相等:

function keys_are_equal($array1, $array2) {
  return !array_diff_key($array1, $array2) && !array_diff_key($array2, $array1);
}

#2


4  

Use array_keys to get array of keys and then use array_diff.

使用array_keys獲取鍵數組,然后使用array_diff。

OR

Use array_diff_key directly.

直接使用array_diff_key。

#3


3  

How about using === instead? You know, the operator for equality?

如何使用===代替?你知道,運營商是否平等?

$array1 = array(
    'abc' => 46,
    'def' => 134,
    'xyz' => 34
);


$array2 = array(
    'abc' => 46,
    'def' => 134,
    'xyz' => 34,
);


var_dump( array_keys( $array1 ) === array_keys( $array2 ) );

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/06/06/720a7e25ad17089707ff616f8146e024.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com