查找两个平面数组的值交集
我希望帮助完成我的函数,该函数比较两个数组并返回两个数组中相同的元素的值。
$array1 = array("bob", "mike", "david", "gary");
$array2 = array("susan", "jenny", "mike");
这两个数组每次都会有不同数量的元素。我运行下面的函数,它说有匹配项,但不会告诉我哪些匹配项。如果数组没有相同数量的元素,我的函数也能工作吗?
echo find_matches($array1, $array2);
function find_matches($mac1, $mac2) {
$matches = array();
foreach ($mac1 as $mac) {
if (in_array($mac, $mac2)) {
$matches[] = $mac;
}
}
if ($matches != 0) {
$error_message = "The following numbers match: " . implode(' ', $matches);
return $error_message;
} else {
return true;
}
}
I would like help finishing my function that compares two arrays and returns the values of the element that are the same in both.
$array1 = array("bob", "mike", "david", "gary");
$array2 = array("susan", "jenny", "mike");
The two arrays will have different amounts of elements every time. I run the function below and it says there are matches but wont tell me which ones. Also will my function work if the array does not have the same amount of elements?
echo find_matches($array1, $array2);
function find_matches($mac1, $mac2) {
$matches = array();
foreach ($mac1 as $mac) {
if (in_array($mac, $mac2)) {
$matches[] = $mac;
}
}
if ($matches != 0) {
$error_message = "The following numbers match: " . implode(' ', $matches);
return $error_message;
} else {
return true;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您希望返回匹配项的数量和匹配项本身,您可以使用
array_intersect
:If you're looking to return the number of matches and the matches themselves, you could use
array_intersect
: