开发者

php array comparison index by index

开发者 https://www.devze.com 2023-03-26 10:30 出处:网络
If there are two array variable which contains exact same 开发者_如何学Pythondigits(no duplicate) but shuffled in position.

If there are two array variable which contains exact same 开发者_如何学Pythondigits(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.


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.


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
)


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消