2008-11-03 52 views
1

如果我有一個數組的值基本上是zerofilled字符串表示的各種數字和另一個整數數組,array_intersect()是否仍然匹配不同類型的元素?PHP array_intersect() - 它是如何處理不同類型的?

例如,將這項工作:

$arrayOne = array('0003', '0004', '0005'); 
$arrayTwo = array(4, 5, 6); 

$intersect = array_intersect($arrayOne, $arrayTwo); 

// $intersect would then be = "array(4, 5)" 

...如果不是,這將是完成這一任務的最有效的方法是什麼?只是通過循環和比較,或遍歷和一切轉換爲整數後運行array_intersect(),或...

回答

3

$貓> test.php的

<?php 
$arrayOne = array('0003', '0004', '0005'); 
$arrayTwo = array(4, 5, 6); 

$intersect = array_intersect($arrayOne, $arrayTwo); 

print_r($intersect); 

?> 

$ PHP test.php的

陣列 ( )

$

所以,不,不會。但是,如果你添加

foreach($arrayOne as $key => $value) 
{ 
    $arrayOne[$key] = intval($value); 
} 

你會得到

$ PHP test.php的

陣列 ( [1] => 4 [2] => 5 )

4

From http://it2.php.net/manual/en/function.array-intersect.php

Note: Two elements are considered equal if and only if 
(string) $elem1 === (string) $elem2. 
In words: when the string representation is the same. 

在你的榜樣,$交叉將是一個空數組,因爲5!==「005」和4!==「004」

+0

感謝歐文的格式化修復:) – 2008-11-03 19:08:24