2015-06-01 46 views
1
沒有數組路口

我有以下代碼:測試在PHP

$result = array_intersect($contacts1, $contacts2); 

這產生:

if (empty($result)) { // i.e. NO INTERECTION 

我才意識到:

Array 
(
[21] => 
[22] => 
[23] => 
[24] => 
[25] => 
[26] => 
[28] => 

if語句我有以下這不會作爲不相交的測試工作,因爲會生成許多元素,所有元素的值都爲null。鑑於此,測試2個數組交叉點的最佳方法是什麼?

回答

2

您可以檢查所有值是否爲空(如果您知道數組中不存在空值)。 您可以使用array_filter功能。

例如:

$result = array_filter(array_intersect($contacts1, $contacts2)); 

這樣一來,所有的空值將被移除,並且將結果(如果沒有intersecion存在)將一個空數組。

更新: 正如在評論中所說,這將刪除非空值。 修訂版是使用回調函數:

function filterOnlyNulls($elem) { 
    return $elem !== null; 
} 

$result = array_filter(array_intersect($contacts1, $contacts2), "filterOnlyNulls"); 
3

如果nulls在數組中,然後array_intersect將返回它們作爲在兩個陣列之中。

$contacts1 = array("bob", "jane", NULL, NULL); 
$contacts2 = array("jim", "john", NULL, NULL); 
$result = array_intersect($contacts1, $contacts2); 
print_r($result); 

陣列 ( [2] => [3] => )

可以篩選使用array_filter路口前每個陣列。它需要一個回調函數,但是默認情況下,所有等於FALSE的條目都將被刪除,包括NULL。

$result2 = array_intersect(array_filter($contacts1), array_filter($contacts2)); 
print_r($result2); 

陣列 ( )

使用,如果你想專門只過濾空值,或者你的要求是什麼callback

function mytest($val) { 
    return $val !== NULL; 
} 
$result3 = array_intersect(array_filter($contacts1, "mytest"), array_filter($contacts2, "mytest")); 
print_r($result3); 

陣列 ( )

+0

感謝您的信息,非常實用。 – user61629