php array comparison index by index

北慕城南 提交于 2019-12-25 04:04:01

问题


If there are two array variable which contains exact same digits(no duplicate) but shuffled in position.

Input arrays

arr1={1,4,6,7,8};
arr2={1,7,7,6,8};

Result array

arr2={true,false,false,false,true};

Is there a function in php to get result as above or should it be done using loop(which I can do) only.


回答1:


This is a nice application for array_map() and an anonymous callback (OK, I must admit that I like those closures ;-)

$a1 = array(1,4,6,7,8);
$a2 = array(1,7,7,6,8);

$r = array_map(function($a1, $a2) {
    return $a1 === $a2;
}, $a1, $a2);

var_dump($r);

/*
array(5) {
  [0]=>
  bool(true)
  [1]=>
  bool(false)
  [2]=>
  bool(false)
  [3]=>
  bool(false)
  [4]=>
  bool(true)
}
*/

And yes, you have to loop over the array some way or the other.




回答2:


You could use array_map:

<?php

$arr1= array (1,4,6,7,8) ;
$arr2= array (1,7,7,6,8) ;

function cmp ($a, $b) {
    return $a == $b ;
}

print_r (array_map ("cmp", $arr1, $arr2)) ;
?>

The output is:

Array
(
    [0] => 1
    [1] =>
    [2] =>
    [3] =>
    [4] => 1
)



回答3:


Any way this job is done must be using looping the elements. There is no way to avoid looping.

No metter how you try to attack the problem and even if there is a php function that do such thing, it uses a loop.




回答4:


You could use this http://php.net/manual/en/function.array-diff.php, but it will not return an array of booleans. It will return what data in array 1 is not in array 2. If this doesn't work for you, you will have to loop through them.




回答5:


there's array_diff() which will return an empty array in case they are both equal.

For your spesific request, you'll have to iterate through the arrays and compare each item.



来源:https://stackoverflow.com/questions/6961723/php-array-comparison-index-by-index

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