PHP array_intersect() - how does it handle different types?

六月ゝ 毕业季﹏ 提交于 2019-12-11 04:16:39

问题


If I've got an array of values that are basically zerofilled string representations of various numbers and another array of integers, will array_intersect() still match elements of different types?

For example, would this work:

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

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

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

And if not, what would be the most efficient way to accomplish this? Just loop through and compare, or loop through and convert everything to integers and run array_intersect() after?


回答1:


$ cat > test.php

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

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

print_r($intersect );

?>

$ php test.php

Array ( )

$

So no, it will not. But if you add

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

you will get

$ php test.php

Array ( [1] => 4 [2] => 5 )




回答2:


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.  

In your example, $intersect will be an empty array because 5 !== "005" and 4 !== "004"



来源:https://stackoverflow.com/questions/259457/php-array-intersect-how-does-it-handle-different-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!