比较动态数组(Compare dynamic arrays)

编程入门 行业动态 更新时间:2024-10-24 08:32:29
比较动态数组(Compare dynamic arrays)

我想帮助完成比较两个数组的函数,并返回两者中相同元素的值。

$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; } }

最满意答案

如果您想要返回匹配数和匹配项,可以使用array_intersect :

$matches = array_intersect($array1, $array2);

If you're looking to return the number of matches and the matches themselves, you could use array_intersect:

$matches = array_intersect($array1, $array2);

更多推荐

本文发布于:2023-07-15 05:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1110641.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   动态   Compare   dynamic   arrays

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!