比较动态数组(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);更多推荐
发布评论